Martin Sojka
Martin Sojka

Reputation: 533

Rspec test of the object method call in controller

I want to test that a controller create and update actions call a process method on the MentionService instance.

In controller I have MentionService.new(post).process

This is my current spec:

it "calls MentionService if a post has been submitted" do
  post = Post.new(new_post_params)
  mention_service = MentionService.new(post)
  expect(mention_service).to receive(:process)
  xhr(:post, :create, company_id: company.id, remark: new_post_params)
end

In the controller actions I have:

def create
  ...
  # after save
  MentionService.new(@remark).process
  ...
end

What I get is:

expected: 1 time with any arguments
received: 0 times with any arguments

Any ideas? Thanks.

Upvotes: 1

Views: 3390

Answers (2)

Dani
Dani

Reputation: 1022

If you're not interested with supplying the mock object yourself you can also modify your expectation to:

expect_any_instance_of(MentionService).to receive(:process)

Upvotes: 3

Noel Frostpaw
Noel Frostpaw

Reputation: 4009

The problem is that you're creating a new instance in your test and expect that instance to receive :process which will not work.

Try playing around with this snippet:

let(:service) { double(:service) }

it "calls MentionService if a post has been submitted" do
  expect(MentionService).to receive(:new).with(post).and_return(service)
  expect(service).to receive(:process)
  xhr(:post, :create, company_id: company.id, remark: new_post_params)
end

You need to tell your MentionService class to receive :new and return a mock object, which will receive :process. If that is the case, you know the call sequence succeeded.

Upvotes: 5

Related Questions