【问题标题】:FactoryGirl - NoMethodError when calling def_delegatorsFactoryGirl - 调用 def_delegators 时出现 NoMethodError
【发布时间】: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


    【解决方案1】:

    这段代码

    def_delegators :@menu, :price
    

    还有这段代码

    def price
      menu.price
    end
    

    他们做不同的事情。委托给方法,而不是(不存在的)实例变量

    def_delegators :menu, :price
    

    【讨论】:

    • 就是这样,但我正在关注这个文档ruby-doc.org/stdlib-2.0.0/libdoc/forwardable/rdoc/… 我什么时候应该使用它?
    • @moondaisy:什么时候应该使用什么,委托给实例变量?当您有一个没有阅读器的实例变量时。我,我更喜欢尽可能使用阅读器。
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多