2017-09-08 4 views
0

私はFactoryGirlとRspecを使ってレールをテストしています。def_delegatorsを使って定義したメソッドを使用すると問題が発生しました。例えばFactoryGirl - def_delegatorsを呼び出すときのNoMethodError

このテスト:

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で失敗しています。

答えて

2

このコード

def_delegators :@menu, :price 

そして、このコード

def price 
    menu.price 
end 

彼らは別のことを行います。メソッドに委譲、ない(存在しない)のインスタンス変数

def_delegators :menu, :price 
+0

それだったが、私は、このドキュメントを以下だったことhttp://ruby-doc.org/stdlib-2.0.0/libdoc/forwardable/ rdoc/Forwardable.html私はそれをいつ使うべきですか? – moondaisy

+1

@moondaisy:どのようなときに、インスタンス変数への委任を使用する必要がありますか?読者のないインスタンス変数があるとき。私は可能な限り読者を使うことを好む。 –

関連する問題