有没有办法撤消any_instance的Mocha存根? [英] Is there a way to undo Mocha stubbing of any_instance?

查看:81
本文介绍了有没有办法撤消any_instance的Mocha存根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器规格内,我是否有效?对于某些路由测试,(基于Ryan Bates nifty_scaffold)如下:-

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

再次进行隔离测试时,效果很好.如果我同时为模型和控制器运行规范,则会出现问题.模型测试始终会因为有效而失败?方法已被删除.当控制器测试被拆除时,我是否可以删除any_instance的存根.

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.

推荐答案

您需要手动配置RSpec.

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

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

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

这篇关于有没有办法撤消any_instance的Mocha存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆