[rspec-users] pending tests fail when I switch to mock_with :mocha

David Chelimsky dchelimsky at gmail.com
Fri Nov 12 09:11:27 EST 2010


On Nov 12, 2010, at 7:23 AM, Ole Morten Amundsen wrote:

> First of all, please direct me into how better to search existing threads in this mailing list.

Not sure what you tried already, but:

  http://groups.google.com/group/rspec
  http://old.nabble.com/forum/Search.jtp?query=rspec-users+rspec+mocha

And if all else fails

  http://www.google.com/search?q=rspec-users+rspec+mocha


> Ok to my rspec 2.0.1 mocha 0.9.8 issue: 
> 
> given a controller test
>  before do
>     subject.expects(:authenticate).once
>   end
>  
>   it "should bla bla" do
>    pending "PENDING, shouldn't fail?"
> end
> 
> with 
>    config.mock_with :rspec 
> it's ok: pending, but with 
>    config.mock_with :mocha
> if fails! 
> 
> It expected the authenticate to be called. What do I have to do to make it compatible?
> 
> Reason for using mocha, is
> A: I'm used to it 
> B: I don't know rspec mocks too well, but it notice that these mocks live across tests, breaking unrelated model specs. 

In the future, please be sure to say what versions of rails and ruby you're using as well.

My best guess is that this is a rails-3 app (because rspec-2 doesn't work with rails-2 yet), and the mocha gem is configured in the Gemfile. Unless it says ":require => false", mocha will be loaded regardless of which framework you tell RSpec to use. Assuming this is all correct (or some other mechanism is being used to configure/load the mocha gem), here's the deal:

When you declare an example as pending _inside the example_, RSpec doesn't know the example is pending until it runs the example, so its before blocks are run. Because the mocha gem is loaded, the "expects" method is added to all objects whether the configured framework is :rspec or :mocha, so the before block is not raising an error when the configured mock framework is :rspec, but then the mocha expectations are never verified. This is why it's passing when configured with :rspec.

The fact that it's failing when configured with :mocha is expected, since the before block is being run.

My recommendation has always been to avoid message expectations (expects in mocha, should_receive in rspec) should never be used in before blocks, and this is one of many reasons why. That said, if you want to declare a method pending and ensure that the before blocks are not executed, then use either of these alternatives:

pending "should bla bla" do
  ..
end

it "should bla bla", :pending => true do
  ..
end

Both of these let RSpec know the example is pending before it is run, so RSpec doesn't run the before blocks in these cases.

HTH,
David

> 
> cheers!
> oma



More information about the rspec-users mailing list