1

I'm looking to test that a class method calls a specific instance method. Is there any way to do this? This is the best I've got, but it fails.

describe '#foo' do
  let(:job) { create :job }
  it 'calls job.bar' do
    job.should_receive(:bar)
    Job.foo
  end
end

I need to be sure that the right instance of job is called, not just any instance. I appreciate any help.

4
  • So this test is testing the the instance method #foo calles the instance method #bar on the same instance. You aren't testing class methods at all. Which one is supposed to be an method on the class? Commented Jan 22, 2013 at 21:18
  • Sorry about that. Typo. Fixed it. Commented Jan 22, 2013 at 21:20
  • Awesome, so how does .foo get the instance to call? Is it doing an activerecord .find or something like that? Commented Jan 22, 2013 at 21:21
  • Yep. (filling in space for minimum comment length.) Commented Jan 22, 2013 at 21:30

1 Answer 1

4

You can use stubs on the method by which .foo gets the instance.

For instance:

describe '.foo' do
  let(:job) { create :job }
  it 'calls job.bar' do
    Job.stub(:find).and_return job
    job.should_receive(:bar)
    Job.foo
  end
end

What this does is ensures that the instance that you expect to have methods called on is the one that actually gets used by .foo.

You can add expectations or argument matchers to this, so:

Job.should_receive(:find).with(job.id).and_return(job)

Sign up to request clarification or add additional context in comments.

1 Comment

That's fantastic. Thank you so much. Still learning to use RSpec. Don't have stuff like this quite down yet, but this works great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.