代码之家  ›  专栏  ›  技术社区  ›  moondaisy

FactoryGirl-调用def\u委托人时出现命名错误

  •  0
  • moondaisy  · 技术社区  · 9 年前

    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_委托人,在所有测试中都失败了 NoMethodError

    1 回复  |  直到 9 年前
        1
  •  2
  •   Sergio Tulentsev    9 年前

    此代码

    def_delegators :@menu, :price
    

    def price
      menu.price
    end
    

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

    def_delegators :menu, :price