共有の例を使用して、複数の機能で使用される再利用可能なシナリオを作成できます。
relishapp ページから取られた基本的な例を以下に示します。ご覧のとおり、同じシナリオが複数の機能で使用され、さまざまなクラスがテストされています。つまり、6 つの例が実行されています。
require 'rspec/autorun'
require "set"
shared_examples "a collection" do
let(:collection) { described_class.new([7, 2, 4]) }
context "initialized with 3 items" do
it "says it has three items" do
collection.size.should eq(3)
end
end
describe "#include?" do
context "with an an item that is in the collection" do
it "returns true" do
collection.include?(7).should be_true
end
end
context "with an an item that is not in the collection" do
it "returns false" do
collection.include?(9).should be_false
end
end
end
end
describe Array do
it_behaves_like "a collection"
end
describe Set do
it_behaves_like "a collection"
end
relishapp ページには、パラメーターを使用して共有された例を実行するなど、いくつかの例があります (以下にコピー)。一連の例を実行する前に、パラメーターを使用してさまざまな条件を設定できるはずだと思います (正確なテストがわからないため)。
require 'rspec/autorun'
shared_examples "a measurable object" do |measurement, measurement_methods|
measurement_methods.each do |measurement_method|
it "should return #{measurement} from ##{measurement_method}" do
subject.send(measurement_method).should == measurement
end
end
end
describe Array, "with 3 items" do
subject { [1, 2, 3] }
it_should_behave_like "a measurable object", 3, [:size, :length]
end
describe String, "of 6 characters" do
subject { "FooBar" }
it_should_behave_like "a measurable object", 6, [:size, :length]
end