0

If I have a model

module MyModule
  def bar(str)
    puts str
  end
end

MyModel < ActiveRecord::Base
  include MyModule
  bar('foo')
end

My spec:

describe MyModel do
  before do
    described_class.stubs(:bar)
  end

  it 'calls bar with correct arguments' do
    # This does not work because it is called before it gets stubbed
    expect(described_class).to have_received(:bar).with('foo')
  end
end

How can I spy on MyModule#bar when called from MyModel?

Using rspec-rails 2.99 and mocha 0.13.3

Pants
  • 2,563
  • 1
  • 20
  • 34
  • 1
    Please provide a [mcve]. Your code doesn't make sense. Is `MyModule` a class, or a module? Currently it's a class *and* a module, and it includes itself??! Where is the `bar` method defined? What does your test look like? – Tom Lord May 22 '19 at 16:56
  • 1
    How have you tried to set up the spy currently? What result do you expect? What result do you get? If there's an error, what does it say? – Tom Lord May 22 '19 at 16:58
  • Is this what you are looking for? [`RSpec: how to test if a method was called?`](https://stackoverflow.com/questions/21262309/rspec-how-to-test-if-a-method-was-called) – Martin May 22 '19 at 17:10
  • `MyModule` is a module with a method `bar`. `bar` gets called by `MyModel` which includes `MyModule`. Maybe you misread the names? The issue as you may know is ActiveRecord models are defined and consequently call `bar` before Rspec even begins running. – Pants May 22 '19 at 22:26
  • @TomLord I added more details – Pants May 23 '19 at 13:19

1 Answers1

2

If you call elsewhere MyModel.new.bar, you can write in the test

expect_any_instance_of(MyModel).to receive(:bar)

If you want to use 'spy', you can use:

allow_any_instance_of(MyModel).to receive(:bar)

If you have link to your MyModel instance inside the test, you can rewrite above examples such way:

expect(my_model_instance).to receive(:bar)

or

allow(my_model_instance).to receive(:bar)

You should understand that after including any module into you class, instance of that class will be receiver of the method.

Foton
  • 56
  • 1
  • 3