如何使用 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/