Skip to content
This repository was archived by the owner on Nov 30, 2024. It is now read-only.

Commit 72c4138

Browse files
committed
Merge pull request #2098 from bootstraponline/example_duplicate_with
Add duplicate_with for RSpec Example
2 parents 0d93e11 + 659f8f1 commit 72c4138

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/rspec/core/example.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,22 @@ def self.parse_id(id)
124124
id.match(/\A(.*?)(?:\[([\d\s:,]+)\])?\z/).captures
125125
end
126126

127+
# Duplicates the example and overrides metadata with the provided
128+
# hash.
129+
#
130+
# @param metadata_overrides [Hash] the hash to override the example metadata
131+
# @return [Example] a duplicate of the example with modified metadata
132+
def duplicate_with(metadata_overrides={})
133+
new_metadata = metadata.clone.merge(metadata_overrides)
134+
135+
RSpec::Core::Metadata::RESERVED_KEYS.each do |reserved_key|
136+
new_metadata.delete reserved_key
137+
end
138+
139+
Example.new(example_group.clone, description.clone,
140+
new_metadata, new_metadata[:block])
141+
end
142+
127143
# @attr_reader
128144
#
129145
# Returns the first exception raised in the context of running this

spec/rspec/core/example_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,21 @@ def metadata_hash(*args)
4040
end
4141
end
4242

43+
describe '#duplicate_with' do
44+
it 'successfully duplicates an example' do
45+
example = example_group.example { raise 'first' }
46+
example2 = example.duplicate_with({ :custom_key => :custom_value })
47+
48+
# ensure metadata is unique for each example
49+
expect(example.metadata.object_id).to_not eq(example2.metadata.object_id)
50+
expect(example.metadata[:custom_key]).to eq(nil)
51+
expect(example2.metadata[:custom_key]).to eq(:custom_value)
52+
53+
# cloned examples must have unique ids
54+
expect(example.id).to_not eq(example2.id)
55+
end
56+
end
57+
4358
describe "#exception" do
4459
it "supplies the exception raised, if there is one" do
4560
example = example_group.example { raise "first" }

0 commit comments

Comments
 (0)