Kyryl Ωliinyk
Kyryl Ωliinyk

Reputation: 146

How can I test class method that creates instance?

I have such a class:

class BaseService
  def self.call(*args)
    new(*args).call
  end
end

I need to test that #self.call creates new instance with given arguments and sends it :call message. How is it possible? Thanx in advance!

Upvotes: 0

Views: 75

Answers (1)

spickermann
spickermann

Reputation: 106882

I would do the following

let(:arguments) { [:foo, :bar] }
let(:base_service) { instance_double('BaseService') } 

before do 
  allow(BaseService).to receive(:new).with(*arguments).and_return(base_service)
  allow(base_service).to receive(:call).with(no_args)
end

it "does the expected thing" do
  BaseService.call(*arguments)

  expect(BaseService).to have_received(:new).with(*arguments).once
  expect(base_service).to have_received(:call).once
end

Another (and perhaps better) option might be to test that BaseService.call(*arguments) has the expected output or side-effects. But because you didn't write what new(*args).call actually does I cannot make a suggestion for that.

Upvotes: 2

Related Questions