Owen Owen - 1 year ago 105
Ruby Question

Actual method being called instead of stub'd version

I am running a Chef spec unit test using the command below. The relevant code is shown further below. I expected some_test_data to be used in the unit test instead of method_name actually getting called. But what is happening is that the stub is not used. Instead method_name does actually get called, which in this case is not appropriate in the unit test. What am I mis-understanding or doing wrong here? Thank you.

rspec spec/unit/mytest_spec.rb

# Code from Chef Spec mytest_spec.rb unit test
allow(ClassName).to receive(:method_name).and_return(some_test_data)

# Code unit test is testing
my_variable = method_name(node)

# Method that gets called above
def self.method_name(node)
# Do something

Answer Source

Actually you're passing a parameter to method_name but in the stubbed method, you're not stubbing out the parameters. That is why the stubbed method doesn't get called when you run the tests.

It should be

allow(ClassName).to receive(:method_name).with('argument').and_return(some_test_data)    

[I am not sure about the following because you didn't post the actual code. You can ignore it if my assumption is wrong]

You're testing a class method, but you're not calling it on the class. ie.

Shouldn't my_variable = method_name(node) be my_variable = Classname.method_name(node) ?

For more, see https://relishapp.com/rspec/rspec-mocks/v/2-99/docs/method-stubs and https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/setting-constraints/matching-arguments

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download