Denny Mueller
Denny Mueller

Reputation: 3615

rspec .to receive(:method_name) correct usage

reduced code:

class Object
  def foo
    (bar / 100).round(2)
  end

  def bar
    self.some_integer
  end
end

I wanted to test that foo calls bar so my spec looks like this

it 'calls #bar upon self' do
  expect(@object).to receive(:bar)
  @object.foo
end

Unfortunately the spec then fails because when calling @object.foo the #bar is nil and fails on the division. Its impossible that #bar returns a nil value thats ensured before. How do I test this correctly?

Upvotes: 0

Views: 71

Answers (1)

Rodrigo
Rodrigo

Reputation: 4802

You should declare which bar value you're expecting for this test:

expect(@object).to receive(:bar).and_return(10)

Docs

EDIT

you can also (thanks @meta):

expect(@object).to receive(:bar).and_call_original

Upvotes: 1

Related Questions