4

Within my controller specs I am stubbing out valid? for some routing tests, (based on Ryan Bates nifty_scaffold) as follows :-

it "create action should render new template when model is invalid" do
  Company.any_instance.stubs(:valid?).returns(false)
  post :create
  response.should render_template(:new)
end

This is fine when I test the controllers in isolation. I also have the following in my model spec

it "is valid with valid attributes" do
  @company.should be_valid
end

Again this works fine when tested in isolation. The problem comes if I run spec for both models and controllers. The model test always fails as the valid? method has been stubbed out. Is there a way for me to remove the stubbing of any_instance when the controller test is torn down.

I have got around the problem by running the tests in reverse alphabetic sequence to ensure the model tests run before the controllers but I really don't like my tests being sequence dependant.

Vega
  • 27,856
  • 27
  • 95
  • 103
Steve Weet
  • 28,126
  • 11
  • 70
  • 86

3 Answers3

4

You need to manually configure RSpec.

Rspec.configure do |config|
  ...

  # == Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr
  # config.mock_with :rspec
end

Also, remember that Rspec provides its own methods to mock an object. Use the RSpec API or you won't be able to benefit from library abstraction. http://rspec.info/documentation/mocks/message_expectations.html

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Although the solution is correct, the explanation is not. Mocha does not detect RSpec, but when the RSpec configuration is set as described, RSpec invokes Mocha at appropriate points. – James Mead Sep 26 '10 at 19:33
3

I'm having the same issue but not using Rspec but normal Test::Unit, actually ActionController::TestCase.

The defined expectations are keeping alive among the tests.

Is there any clue how can I reset my expectations between tests?

  • Ruby: 1.9.2
  • Rails: 3.0.3
  • Mocha: 0.9.10

Updated: I have solved this with the unstub Mocha method: http://mocha.rubyforge.org/classes/Mocha/ObjectMethods.html#M000009

fguillen
  • 36,125
  • 23
  • 149
  • 210
1

Does your spec_helper contain

Spec::Runner.configure do |config|
  config.mock_with :mocha
end

With that rspec should tear down mocks between tests.

anshul
  • 5,945
  • 5
  • 24
  • 29