【发布时间】:2017-09-08 17:10:42
【问题描述】:
我正在使用 FactoryGirl 和 Rspec 在 Rails 上进行测试,当我使用使用 def_delegators 定义的方法时遇到了问题。
例如这个测试:
it 'has the weekly discount' do
//I also tried using create here
menu = FactoryGirl.build(:menu, weekly_price: 100, price: 200)
meal = FactoryGirl.build(:meal, menu: menu)
price = meal.price
end
在最后一行失败并出现此错误:
1) Order has the weekly discount
Failure/Error: price = meal.price
NoMethodError:
undefined method `price' for nil:NilClass
# ./spec/models/order_spec.rb:17:in `block (2 levels) in <top (required)>'
这就是Meal中定义价格的方式:
class Meal < ApplicationRecord
extend Forwardable
belongs_to :menu
def_delegators :@menu, :price
end
如果我把它改成这样:
class Meal < ApplicationRecord
extend Forwardable
belongs_to :menu
def price
menu.price
end
end
测试通过。我在其他地方使用 def_delegators 并且在所有测试中都以相同的NoMethodError 失败。
【问题讨论】:
标签: ruby-on-rails ruby rspec factory-bot rspec-rails