Rspec / Rails: how to check if a class method is called

I would like to write something like this:

it 'does not invoke any MyService' do MyService.should_not_receive(<any method>) tested_method end 

I do not want to list all MyService methods explicitly, because this will lead to a fragile test that could give false positives if new methods were added to MyService.

+4
source share
3 answers

What about replacing the implementation with a double?

 it 'does not invoke any MyService' do original_my_service = MyService begin # Replace MyService with a double. MyService = double "should not receive any message" tested_method ensure # Restore MyService to original implementation. MyService = original_my_service end end 

If methods are called in MyService, it should raise:

 RSpec::Mocks::MockExpectationError: Double "should not receive any message" received unexpected message :some_method with (no args) 
+1
source

If you MyService dependency inside your object, you can replace it with a layout without the methods defined on it, so any method call will throw an exception.

Let me show you an example:

 class Manager attr_reader :service def initialize(service = MyService) @service = service end def do_stuff service.do_stuff end def tested_method other_stuff end end 

And the tests will be:

 context "#do_stuff" do let(:manager) { Manager.new } it 'invokes MyService by default' do MyService.should_receive(:do_stuff) manager.do_stuff end end context "#tested_method" do let(:service) { mock("FakeService") } let(:manager) { Manager.new(service) } it 'does not invoke any service' do expect { manager.tested_method }.not_to raise_error end end 
+2
source
 it 'does not invoke MyService' do stub_const('MyService', double) tested_method end 

Any attempt to access MyService will return the mocked RSpec double . Since doubling causes errors when they receive messages that are not explicitly crossed out (and none of them are extinguished), any call to MyService will cause an error.

https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/basics/test-doubles

0
source

Source: https://habr.com/ru/post/1488011/


All Articles