A
A
Anton Ivanov2017-04-19 07:32:52
rspec
Anton Ivanov, 2017-04-19 07:32:52

How to properly write function call checking in RSpec?

Hello.
Not quite me, yet, apparently, I understand the principle of double.
In a test, I need to check that a certain class function is being called. But another function of the same class, at the same time, should work fine.
That is, something like this:

class Api
  def func1 # должна отработать
    ...
  end

  def func2 # надо проверить, что она вызывается
    ...
  end
end

if in the test I write:
expect(Api).to receive(:new).and_return(double(func2: true))
, then I get an error that an unknown function func1 is being called.
If I remove , then, accordingly, func1 is also not called. How to describe correctly? .and_return(double(func2: true))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Ivanov, 2017-04-19
@Fly3110

I solved the problem, but, it seems to me, very, very clumsy, probably better.
The class is initialized three times with three different parameters.
It turned out like this:

api1        = Api.new('param1')
api2        = Api.new('param2')
api_default        = Api.new
allow(Api).to receive(:new).with(no_args).and_return(api_default)
allow(Api).to receive(:new).with('param1').and_return(api1)
allow(Api).to receive(:new).with('param2').and_return(api2)
expect(api_default).to receive(:func2).once

It's annoying that I only check the default instance, but I had to describe everything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question