如何使用RSpec模拟有错误的模型

时间:2011-06-06 06:07:50

标签: ruby-on-rails-3 testing view rspec2

我正在测试我的Rails应用程序的视图层。

此视图适用于客户模型,我在其中调用错误,如此(haml):

- if @customer.errors.present?
  - flash[:warn] = ""
- @customer.errors.full_messages.each do |msg|
  - flash[:warn] += msg + "<br />"

= form_for :customer, :url => customer_registration_path do |f|
  - validated = resource.errors.any?
  .field{ :class => !validated ?  "" : (resource.errors.has_key?(:email) ? "failed" : "passed" )  }
    = f.text_field "email",   :placeholder => "почта", :autocomplete => "off"
    .status
  .field{ :class => !validated ?  "" : (resource.errors.has_key?(:password) ? "failed" : "passed" ) }
    = f.password_field "password", :placeholder => "пароль", :autocomplete => "off"
    .status
  .field{ :class => !validated ?  "" : (resource.errors.has_key?(:password_confirmation) ? "failed" : "passed" ) }
    = f.password_field "password_confirmation", :placeholder => "повторите пароль", :autocomplete => "off"
    .status
  = f.submit "" # Зарегистрироваться

我需要测试“电子邮件”字段中包含的内容,标记为“失败”。

如何为客户模型编写模拟,模拟相应错误的存在?

1 个答案:

答案 0 :(得分:0)

我的做法是制作实际的无效对象,而不是真正的嘲笑粉丝。 但如果你坚持:

it "should render errors" do
  @user = User.new
  @user[:errors][:email] = 'invalid'
  @view.stub!(:resource).and_return { @user }
  render
  ......
end

顺便说一下,我认为您构建的大多数功能都是通过动态表单提供的:https://github.com/joelmoss/dynamic_form