有没有办法撤消any_instance的Mocha存根?

在我的控制器规格中,我的存根有效吗? 对于一些路由测试,(基于Ryan Bates nifty_scaffold)如下: –

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 

当我单独测试控制器时,这很好。 我的模型规格中也有以下内容

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

再次,这在隔离测试时工作正常。 如果我为模型和控制器运行规范,问题就来了。 模型测试总是失败为有效? 方法已被删除。 当控制器测试被拆除时,有没有办法删除any_instance的存根。

我通过以反向字母顺序运行测试来解决问题,以确保模型测试在控制器之前运行,但我真的不喜欢我的测试依赖于序列。

您需要手动配置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 

另外,请记住,Rspec提供了自己的方法来模拟对象。 使用RSpec API或者您将无法从库抽象中受益。 http://rspec.info/documentation/mocks/message_expectations.html

我有同样的问题,但没有使用Rspec而是正常的Test::Unit ,实际上是ActionController::TestCase

定义的期望在测试中保持活跃。

有什么线索可以在测试之间重置我的期望吗?

  • Ruby:1.9.2
  • Rails:3.0.3
  • 摩卡:0.9.10

更新 :我用unstub Mocha方法解决了这个问题: http : unstub

你的spec_helper是否包含

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

因此,rspec应该在测试之间拆除模拟。