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

Add duplicate_with for RSpec Example #2098

Merged
merged 1 commit into from
Oct 23, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/rspec/core/example.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,22 @@ def self.parse_id(id)
id.match(/\A(.*?)(?:\[([\d\s:,]+)\])?\z/).captures
end

# Duplicates the example and overrides metadata with the provided
# hash.
#
# @param metadata_overrides [Hash] the hash to override the example metadata
# @return [Example] a duplicate of the example with modified metadata
def duplicate_with(metadata_overrides={})
new_metadata = metadata.clone.merge(metadata_overrides)

RSpec::Core::Metadata::RESERVED_KEYS.each do |reserved_key|
new_metadata.delete reserved_key
end

Example.new(example_group.clone, description.clone,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The example group should not be cloned. The example should belong to the same example group class, not a copy of it. The clone is likely to cause some bugs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch. I'll submit a fix & update the spec to check this bug.

new_metadata, new_metadata[:block])
end

# @attr_reader
#
# Returns the first exception raised in the context of running this
Expand Down
15 changes: 15 additions & 0 deletions spec/rspec/core/example_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,21 @@ def metadata_hash(*args)
end
end

describe '#duplicate_with' do
it 'successfully duplicates an example' do
example = example_group.example { raise 'first' }
example2 = example.duplicate_with({ :custom_key => :custom_value })

# ensure metadata is unique for each example
expect(example.metadata.object_id).to_not eq(example2.metadata.object_id)
expect(example.metadata[:custom_key]).to eq(nil)
expect(example2.metadata[:custom_key]).to eq(:custom_value)

# cloned examples must have unique ids
expect(example.id).to_not eq(example2.id)
end
end

describe "#exception" do
it "supplies the exception raised, if there is one" do
example = example_group.example { raise "first" }
Expand Down