ruby-on-railsrspecactivesupport-concern

How to mock a method inside concern?


I have FooConcern and BarService as follows:

module FooConcern
  extend ActiveSupport::Concern

  def notify_slack(message)
    # send message to slack
  end
end
class BarService
  include FooConcern

  def run
    # do some stuff
    message = 'blah, blah'
    notify_slack(message)
  end
end

How can I write to mock notify_slack so I don't actually call slack API when I run Rspec test for BarService#run ?

RSpec.describe BarService do
  describe 'run' do
    subject { described_class.new.run }

    it do
      # some tests on things other than notifying slack
    end
  end
end

Solution

  • You can use allow to mock that method.

    RSpec.describe BarService do
       describe 'run' do
         subject { described_class.new }
    
         it do
           allow(subject).to receive(:notify_slack).and_return(true)
           # some tests on things other than notifying slack
           subject.run
         end
       end
     end