我会对现有的测试套件做两件事,以便它可以实时使用,第一件事是使用 describe 和 it 块获取元数据 (There's a good blog post on it here) 的功能。第二个使用shared_contexts的能力来阻止。
首先,使用元数据标记您希望针对真实 API 运行的规范。例如,您想知道这些可以真实运行,例如
describe "Hitting the API with a call", :can_be_real do
# …
end
然后可以从命令行using the tag option 运行这些规范。
第二件事,是用真实的东西代替模拟物。这取决于您如何定义模拟,是使用before 还是let,以及您模拟了多少。作为一个愚蠢的例子,见下文:
require 'rspec'
RSpec.configure do |c|
c.treat_symbols_as_metadata_keys_with_true_values = true
end
shared_context "all my mocks and stubs" do
let(:this) { false }
end
describe "a", :real do
include_context "all my mocks and stubs" do
let(:this) { true } if ENV["REAL_API_CALL"] == 'true'
before do
stub_const( "URI", Class.new ) unless ENV["REAL_API_CALL"] == 'true'
end
end
it "should be real when it's real" do
this.should == true
end
it "should escape things when it's real" do
URI.should respond_to :escape
end
end
当文件通过bin/rspec example.rb 运行时,输出为:
a
should be real when it's real (FAILED - 1)
should escape things when it's real (FAILED - 2)
Failures:
1) a should be real when it's real
Failure/Error: this.should == true
expected: true
got: false (using ==)
# ./example.rb:19:in `block (2 levels) in <top (required)>'
2) a should escape things when it's real
Failure/Error: URI.should respond_to :escape
expected URI to respond to :escape
# ./example.rb:22:in `block (2 levels) in <top (required)>'
Finished in 0.00349 seconds
2 examples, 2 failures
当通过env REAL_API_CALL=true bin/rspec example.rb运行时:
a
should be real when it's real
should escape things when it's real
Finished in 0.00301 seconds
2 examples, 0 failures
因此,您可以通过多种方式更改规范的上下文,从而允许您从命令行(以及因此,Jenkins)获得所需的控制级别。您可能希望使用其他元数据来标记规范,例如真实运行是否安全、是否可能需要很长时间等。