gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:10:26 26 4
gpt4 key购买 nike

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

undefined method `key?' for 1014:Fixnum

我的模型实例的 stub 在我的路由测试中可以正常工作,但在这里却不尽如人意。我做错了什么?

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)>'

最佳答案

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

正如@Зелёный 已经提到的,您需要实际将记录保存到数据库中,以便能够在 Controller 规范中使用它。

为避免重复问题和测试顺序问题,您应该在每个示例之间清空数据库。 database_cleaner gem 对于这项任务来说是无价的。

此外,如果您需要在同一个规范中创建多个记录,您可以在 factory girl 中使用序列:

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) }

关于ruby-on-rails - RSpec - 未定义的方法 `key?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com