Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to stub all methods of a particular class in RSpec 3?

I have a self-made service class that is helping me DRY up the sending of push notifications and I'd like to be able to stub all methods belonging to the class.

I'm thinking of something like

# Service Class
class PushService
  def self.send_message
    ...
  end

  def self.send_payment_confirmation
    ...
  end
end

In my spec tests, I'd like to be able to do

RSpec.describe "blah" do
  before do
    allow(PushService).to receive_everything.and_return({})
  end

end

I've looked around and it appears that stub_everything() has been deprecated and it is recommended to use double's as_null_object but I'm not sure how that works.

Can anyone help?

like image 313
David C Avatar asked Oct 19 '22 00:10

David C


1 Answers

Yes, stub_everything is deprecated.

Yes, you can use as_null_object to stub everything in your test like this:

let(:push_service) { double(PushService).as_null_object }

When you use as_null_object, your object will respond to any method that is not implemented. It will also allow you to use explicit stubs and explicit expectations.

See Null object doubles documentation for more information.

like image 148
K M Rakibul Islam Avatar answered Oct 27 '22 18:10

K M Rakibul Islam