rspec shared examples
# Define a shared example group for objects that respond to certain methods
RSpec.shared_examples "responds to basic methods" do |object|
it "responds to #foo" do
expect(object).to respond_to(:foo)
end
it "responds to #bar" do
expect(object).to respond_to(:bar)
end
end
# Implementing the shared example group in a spec file
RSpec.describe MyClass do
it_behaves_like "responds to basic methods", MyClass.new
end
Explanation:
RSpec.shared_examples "responds to basic methods" do |object|
Defines a shared example group named "responds to basic methods" that takes an object as a parameter.
it "responds to #foo" do ... end
Inside the shared example group, defines an example that checks whether the provided object responds to the
#foo
method using RSpec'sexpect
syntax.it "responds to #bar" do ... end
Another example within the shared example group, verifying whether the object responds to the
#bar
method.RSpec.describe MyClass do ... end
Defines an RSpec example group for
MyClass
.it_behaves_like "responds to basic methods", MyClass.new
- Uses the shared example group
responds to basic methods
by callingit_behaves_like
, passing inMyClass.new
as the object to be tested against the shared examples. This ensures that instances ofMyClass
respond to#foo
and#bar
methods as specified in the shared examples.