【问题标题】:Replace method implementation when stubbing with mocha使用 mocha 存根时替换方法实现
【发布时间】:2014-12-25 07:18:37
【问题描述】:

我已经习惯了 RSpec,您可以在其中使用 evalueted lazily 的块来存根方法实现。

现在我正在处理一个使用 Test::Unit 和 mocha 作为模拟库的项目的拉取请求。

我需要能够做一些类似于 rspec 示例的事情,即将方法实现替换为取决于对象状态的动态实现,因此我不能使用 mocha #returns 方法提供的静态调用。

有什么方法可以使用 mocha 获得相同的功能,我找不到任何关于此的文档?

我需要实现类似的东西(RSpec 2.14 语法)

class SomeController < ApplicationController
  before_filter :authenticate

  def authenticate
    # original method I need to replace
  end

  def some_other_method
    :bar
  end

end

describe SomeController do

  before do
    controller.stub :authenticate do
      redirect_to root_path if some_other_method == :foo
    end
  end

  it 'should test something' do
    controller.stub(some_other_method: :foo)
    get :index
    response.should redirect_to root_path
  end

  it 'should test something else' do
    get :index
    response.should be_successful
  end

end

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec stubbing


    【解决方案1】:

    您不能只在controller 实例上使用def 吗?

    def controller.some_other_method
      :foo
    end
    

    【讨论】:

    • 我自己在实验时得出了相同的答案。通常最简单的事情是最有效的。整个示例比我发布的更复杂,但是我可以重构测试以使用这种方法。
    • 这之后如何清理并恢复原来的定义?
    • 您可以为旧方法设置别名,然后以相反的方式恢复它,或者您可以使用改进来仅在当前规范文件中进行更改。但是,如果可以的话,我会建议使用不同的库,一个支持动态存根的库。比如rr.github.io/rr虽然我自己没用过。
    • Mocks 并不是真的要像这样使用,这里有一篇关于不同类型测试替身的精彩文章:martinfowler.com/articles/mocksArentStubs.html
    猜你喜欢
    • 2018-06-20
    • 2013-01-06
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多