【问题标题】:Wrong with mock_model in rspec?rspec 中的 mock_model 错误?
【发布时间】:2011-10-21 15:55:24
【问题描述】:

这是用于在客户控制器中测试节目的 rspec 代码:

it "'show' should be successful" do
  #category = Factory(:category)
  #sales = Factory(:user)
  #customer = Factory(:customer, :category1_id => category.id, :sales_id => sales.id)
  category = mock_model('Category')
  sales = mock_model('User')
  customer = mock_model(Category, :sales_id => sales.id, :category1_id => category.id)

  get 'show' , :id => customer.id
  response.should be_success
end

这是 rspec 中的错误:

CustomersController GET customer page 'show' should be successful
     Failure/Error: get 'show' , :id => customer.id
     ActiveRecord::RecordNotFound:
       Couldn't find Customer with id=1003
     # c:in `find'
     # ./app/controllers/customers_controller.rb:59:in `show'
     # ./spec/controllers/customers_controller_spec.rb:50:in `block (3 levels) in <top (required)>'

rspec 测试通过 Factory 创建的真实记录(参见 rspec 代码中的#ed)

模拟有什么问题?谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 rspec2


    【解决方案1】:

    规范在控制器的操作中失败,除非您明确告知,否则控制器对您的模拟一无所知。

    将此添加到您的规范中,在 get 语句之前。

    Customer.should_receive(:find).and_return(customer)
    

    【讨论】:

    • 得到错误:6) CustomersController GET customer page 'show' 应该成功失败/错误:get 'show' , :id => customer.id ActionView::Template::Error: undefined method @ 987654323@_app_views_customers_show_html_erb___69786027_34474944' # ./spec/controllers/customers_controller_spec.rb:51:in `block (3 levels) in '. show.html.erb 中的第 15 行是:
    • 为什么渲染视图是控制器规范?好吧,如果你想让它工作,要么创建一个包含所有模型属性的模拟,要么使用一个真实的对象。
    • 模拟是否为对象生成所有字段?它必须为伪造的对象填写一些东西。实物有效。
    • 模拟默认是空的,你必须告诉它如何表现。这是正常的,它适用于普通对象。无论如何,控制器的规范不是测试视图的地方,你应该禁用它。
    • 对于 RSpec 3,我使用了“期望”方法而不是“应该接收”:expect(Customer).to receive(:find).and_return(customer)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多