【问题标题】:Is there a way to undo Mocha stubbing of any_instance?有没有办法撤销 any_instance 的 Mocha 存根?
【发布时间】:2010-04-23 08:31:24
【问题描述】:

在我的控制器规格范围内,我是否有效?对于一些路由测试,(基于 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 的存根。

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

【问题讨论】:

    标签: ruby-on-rails ruby rspec ruby-mocha


    【解决方案1】:

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

    【讨论】:

    • 虽然解法是对的,但解释是不对的。 Mocha 不会检测 RSpec,但是当 RSpec 配置按照描述设置时,RSpec 会在适当的点调用 Mocha。
    • 更新了评论。谢谢@floehopper
    【解决方案2】:

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

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

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

    • 红宝石:1.9.2
    • 导轨:3.0.3
    • 摩卡:0.9.10

    更新:我已经用unstub Mocha 方法解决了这个问题:http://mocha.rubyforge.org/classes/Mocha/ObjectMethods.html#M000009

    【讨论】:

      【解决方案3】:

      你的 spec_helper 是否包含

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

      使用该 rspec 应该在测试之间拆除模拟。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-25
        • 2023-03-15
        • 1970-01-01
        • 2019-04-14
        • 1970-01-01
        相关资源
        最近更新 更多