[ rails ] rspec : write share example : shared_examples_for / it_behaves_like

Shared example groups

When declared, a shared group’s content is stored. It is only realized in the
context of another example group, which provides any context the shared group
needs to run.

A shared group is included in another group using the it_behaves_like() or
it_should_behave_like() methods.

collection_spec.rb

require "set"

shared_examples_for "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

Run

Array
behaves like a collection
initialized with 3 items
says it has three items
#include?
with an an item that is in the collection
returns true
with an an item that is not in the collection
returns false

Set
behaves like a collection
initialized with 3 items
says it has three items
#include?
with an an item that is in the collection
returns true
with an an item that is not in the collection
returns false

ref : https://www.relishapp.com/rspec/rspec-core/v/2-0/docs/example-groups/shared-example-group

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s