RSpec - 未定义的方法`key?'

时间:2015-08-01 19:55:34

标签: ruby-on-rails testing rspec tdd shoulda

我正在尝试运行测试以渲染模板并遇到错误:

undefined method `key?' for 1014:Fixnum

我的模型实例的存根在我的路由测试中应该正常工作,但在这里没有那么多。我做错了什么?

describe RestaurantsController do
  let(:restaurant) { FactoryGirl.build_stubbed(:restaurant) }

  describe 'GET #show' do
    before { get :show, restaurant.id }

    it { should render_template('show') }
  end
end

完整错误

 1) RestaurantsController GET #show 
     Failure/Error: before { get :show, restaurant.id }
     NoMethodError:
       undefined method `key?' for 1014:Fixnum
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_controller/test_case.rb:744:in `html_format?'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_controller/test_case.rb:598:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_controller/test_case.rb:65:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/devise-3.5.1/lib/devise/test_helpers.rb:19:in `block in process'
     # /Library/Ruby/Gems/2.0.0/gems/devise-3.5.1/lib/devise/test_helpers.rb:72:in `catch'
     # /Library/Ruby/Gems/2.0.0/gems/devise-3.5.1/lib/devise/test_helpers.rb:72:in `_catch_warden'
     # /Library/Ruby/Gems/2.0.0/gems/devise-3.5.1/lib/devise/test_helpers.rb:19:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.0/lib/action_controller/test_case.rb:505:in `get'
     # ./spec/controllers/restaurants_controller_spec.rb:15:in `block (3 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:2)

get采取行动和参数的散列(除其他外)。它不会隐含地采用模型并将其转换为{ id: model.to_param }

相反,您需要明确指定参数。

describe RestaurantsController do
  let(:restaurant) { create(:restaurant) }

  subject { response }

  describe 'GET #show' do
    before { get :show, id: restaurant }
    it { should render_template('show') }
  end
end

正如@Зелёный已经提到过,您需要将记录实际保存到数据库中才能在控制器规范中使用它。

为避免重复问题和测试排序问题,您应在每个示例之间清空数据库。 database_cleaner gem对于该任务非常宝贵。

此外,如果您需要在同一规范中创建多个记录,则可以使用工厂女孩中的序列:

FactoryGirl.define do
  factory :user do
    email { |n| "test-#{n}@example.com" }
  end
end

gem ffaker非常适合生成电子邮件,用户名等。

加了:

您可以通过在rails_helper

中添加方法来设置FactoryGirl的快捷方式
RSpec.configure do |config|
  # ...
  config.include FactoryGirl::Syntax::Methods
end

这使您可以使用FactoryGirl方法而无需输入模块名称,如下所示:

let(:restaurant) { create(:restaurant) }