Masha
Masha

Reputation: 327

Mocha expects method

So my situation is: I have a 2 modules that have the same structure like that:

module Module1
  class Config

    def fee_rate
      2
    end
  end
end

So, say, Module2 would have class Config with the method fee_rate, just with a different value (those are actually implemented in a rails engine, but it shouldn't matter)

and then my model can use either Module1 or Module2 to get the fee rate value like that:

def config
  @config ||= "#{module_name.titleize}::Config".constantize.new
  @config
end

def get_value
  config.get_fee * some_other_value
end

What I'm trying to test is if get_fee function was called on the correct class:

"#{model.module_name.titleize}::Config".constantize.any_instance.expects(:get_fee).at_least_once
model.get_value

and on the line when I call get_value I get the following error - undefined method `*' for nil:NilClass. I'm completely lost now, so I'd appreciate any help and ideas.

Upvotes: 1

Views: 2253

Answers (1)

Shadwell
Shadwell

Reputation: 34784

By setting up an expectation for get_fee you are preventing the actual method call from happening. Because you haven't set a return value for the expectation, e.g. expects(:get_fee).at_least_once.returns(3) it is returning nil, hence the error message.

You may have more success by doing away with the expectation altogether and checking that the right type of config class is created, e.g.

model.get_value
assert_equal "#{model.module_name.titleize}::Config".constantize, 
             model.config.class

Upvotes: 2

Related Questions