Search code examples
ruby-on-railsrubyrspecfactory-botrspec-rails

FactoryGirl - NoMethodError when calling def_delegators


I'm using FactoryGirl and Rspec for testing on rails, and I have come across a problem when I use methods that are define using def_delegators.

For example this test:

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

Fails on the last line with this error:

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)>'

And this is how price is defined in Meal:

class Meal < ApplicationRecord
  extend Forwardable
  belongs_to :menu

  def_delegators :@menu, :price
end

If I change it to this:

class Meal < ApplicationRecord
  extend Forwardable
  belongs_to :menu

  def price
    menu.price
  end
end

The test passes. I use def_delegators in other places and in all the tests have been failing with the same NoMethodError.


Solution

  • This code

    def_delegators :@menu, :price
    

    And this code

    def price
      menu.price
    end
    

    they do different things. Delegate to the method, not the (non-existing) instance variable

    def_delegators :menu, :price