FactoryGirl - 调用时出现 NoMethodError def_delegators
FactoryGirl - NoMethodError when calling def_delegators
我正在使用 FactoryGirl 和 Rspec 在 rails 上进行测试,当我使用使用 def_delegators
.[=18= 定义的方法时遇到了问题]
例如这个测试:
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
.
失败
这个代码
def_delegators :@menu, :price
还有这段代码
def price
menu.price
end
他们做不同的事情。委托给方法,而不是(不存在的)实例变量
def_delegators :menu, :price
我正在使用 FactoryGirl 和 Rspec 在 rails 上进行测试,当我使用使用 def_delegators
.[=18= 定义的方法时遇到了问题]
例如这个测试:
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
.
这个代码
def_delegators :@menu, :price
还有这段代码
def price
menu.price
end
他们做不同的事情。委托给方法,而不是(不存在的)实例变量
def_delegators :menu, :price