sclarson
sclarson

Reputation: 4422

RSpec should_receive not reaching method in class

New to ruby/rspec and trying to test that a method raises an exception. I may be going about this entirely incorrectly.

#require 'rspec'

describe "TestClass" do
  it "should raise exception when my method is called" do
    test = Test.new
    test.should_receive(:my_method).and_raise
  end
end

class Test
  def my_method
    raise
  end
end  


rspec test.rb
F

Failures:

  1) TestClass should raise exception when my method is called
     Failure/Error: test.should_receive(:my_method).and_raise
       (#<Test:0x007fc61c82f7c8>).my_method(any args)
           expected: 1 time
           received: 0 times
     # ./test.rb:6:in `block (2 levels) in <top (required)>'

Finished in 0.00061 seconds
1 example, 1 failure

Failed examples:

rspec ./test.rb:4 # TestClass should raise exception when my method is called

Why is the message received zero times?

Upvotes: 0

Views: 1101

Answers (2)

Gavin Miller
Gavin Miller

Reputation: 43815

Your test is wrong. In order to test that an exception is raised you'll want to do this:

it "should raise exception when my method is called" do
  test = Test.new
  test.should_receive(:my_method)

  expect {
    test.my_method
  }.to raise_error      
end

And in this case you likely don't need to add should_receive. By calling my_method you're making sure that test is receiving that method. Basically you're mocking when you don't need to mock.

Upvotes: 1

ck3g
ck3g

Reputation: 5929

You have to do something to call that method. If it is callback here is examples how to test them.

Upvotes: 0

Related Questions