Simplecov 检测到我在lib/api_verson.rb
课堂上遗漏了一些测试:
class ApiVersion
def initialize(version)
@version = version
end
def matches?(request)
versioned_accept_header?(request) || version_one?(request)
end
private
def versioned_accept_header?(request)
accept = request.headers['Accept']
accept && accept[/application\/vnd\.#{Rails.application.secrets.my_app_accept_header}-v#{@version}\+json/]
end
def unversioned_accept_header?(request)
accept = request.headers['Accept']
accept.blank? || accept[/application\/vnd\.#{Rails.application.secrets.my_app_accept_header}/].nil?
end
def version_one?(request)
@version == Rails.application.secrets.my_app_default_api_version && unversioned_accept_header?(request)
end
end
路由文件使用此类来帮助设置 api 版本:
namespace :api, path: "", defaults: {format: :json} do
scope module: :v1, constraints: ApiVersion.new(1) do
get '/alive', to: 'api#alive'
end
scope module: :v2, constraints: ApiVersion.new(2) do
get '/alive', to: 'api#alive'
end
end
此设置是从versioning_your_ap_is移植的。
我正在尝试在这里测试 simplecov 报告为失败的方法,现在我陷入了私有方法包含私有方法的情况......
def version_one?(request)
@version == Rails.application.secrets.my_app_default_api_version && unversioned_accept_header?(request)
end
这是我目前的规格:
require 'spec_helper'
describe ApiVersion do
before(:each) do
@apiversion = ApiVersion.new(1)
@current_api_version = Rails.application.secrets.my_app_default_api_version
@request = ActionController::TestRequest.new(host: 'localhost')
@request.headers["Accept"] = "application/vnd.#{Rails.application.secrets.my_app_accept_header}-v#{@current_api_version}+json"
end
describe "Method #versioned_accept_header? =>" do
it "Should return false if the header accept variable contains application/vnd.#{Rails.application.secrets.my_app_accept_header}-v#{@current_api_version}+json" do
expect(@apiversion.send(:unversioned_accept_header?, @request)).to eq(false)
end
it "Should return true if no version is included with the header" do
request = @request
request.headers["Accept"] = nil
expect(@apiversion.send(:unversioned_accept_header?, request)).to eq(true)
end
end
describe "Method #version_one? =>" do
it "test me" do
# @apiversion.send(:unversioned_accept_header?, @request)
binding.pry
# expect(@apiversion.send(:version_one?, @request)).to eq(false)
end
end
end
如何存根嵌套的私有方法来测试 version_one 私有方法?