ruby - 模型中的 RSpec 模拟或 stub super

标签 ruby unit-testing module mocking rspec

如何使用 super 测试模块的这一小部分? (父类(super class)是 action_dispatch-3.0.1 testing/integration...)该模块包含在 spec/requests 中以拦截 post:

module ApiDoc
  def post(path, parameters = nil, headers = nil)
    super
    document_request("post", path, parameters, headers) if ENV['API_DOC'] == "true"
  end
  ...
end

我不希望它运行 ActionDispatch::Integration-whatever,但我不知道如何模拟或 stub super 来对其进行单元测试。

该模块仅在规范内使用,并且将具有 100% 的测试覆盖率,这证明这些指标是无用的。我需要对其进行单元测试。

一个例子,如果需要的话,这就是我使用模块 ApiDoc 的方式

require 'spec_helper'

describe "Products API" do
  include ApiDoc  ############## <---- This is my module
  context "POST product" do
    before do
      @hash = {:product => {:name => "Test Name 1", :description => "Some data for testing"}}
    end

    it "can be done with JSON" do
      valid_json = @hash.to_json
      ############### the following 'post' is overriden by ApiDoc
      post("/products.json",valid_json,
       {"CONTENT_TYPE" => "application/json",
        "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials("user", "secret")})
      response.should be_success
    end
  end
end

最佳答案

您可以检查是否在“ super ”类上调用了该方法

ActionDispatch::Integration.any_instance.should_receive(:post)

由于 ApiDock 仅用于您的测试,您还可以使用 alias_method_chain 覆盖 post 方法:

ActionDispatch::Integration.instance_eval do
  def post_with_apidoc(path, parameters = nil, headers = nil)
    post_without_apidoc
    if ENV['API_DOC'] == "true"
      document_request("post", path, parameters, headers)
    end
  end
  alias_method_chain :post, :apidoc
end

关于ruby - 模型中的 RSpec 模拟或 stub super ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4286320/

相关文章:

mysql - Rails安装mysql错误

perl - 将 CruiseControl 转换为 Hudson

asp.net - 在 DotNetNuke 6 中创建模块并进行调试的最简单方法

ruby-on-rails - LEFT OUTER 加入 Rails 3

ruby - 让 Ruby block /命令在没有空白 'rescue' block 的情况下静默失败

c# - Rhino Mocks,设置 stub 属性后如何执行操作

c# - 您如何测试是否已创建对象的新实例?

java - 如何测试一个ListActivity?

android - Android 两个模块之间的通信

ruby-on-rails - rails : Can't include scss in rails 4. 1.1。 - 类型错误:对象不支持此属性或方法