Skip to content

Commit

Permalink
yield the example to the block passed to let or subject
Browse files Browse the repository at this point in the history
  • Loading branch information
dchelimsky committed Jun 19, 2013
1 parent 6e02be3 commit 4f3f66a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/rspec/core/memoized_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,10 @@ def let(name, &block)

# Apply the memoization. The method has been defined in an ancestor
# module so we can use `super` here to get the value.
define_method(name) do
__memoized.fetch(name) { |k| __memoized[k] = super(&nil) }
if block.arity == 1
define_method(name) { __memoized.fetch(name) { |k| __memoized[k] = super(@_current_rspec_example, &nil) } }
else
define_method(name) { __memoized.fetch(name) { |k| __memoized[k] = super(&nil) } }
end
end

Expand Down
33 changes: 33 additions & 0 deletions spec/rspec/core/memoized_helpers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ def subject_value_for(describe_arg, &block)
end

describe "explicit subject" do
it "yields the example in which it is eval'd" do
example_yielded_to_subject = nil
example_yielded_to_example = nil

group = ExampleGroup.describe
group.subject { |e| example_yielded_to_subject = e }
group.example { |e| subject; example_yielded_to_example = e }
group.run

expect(example_yielded_to_subject).to eq example_yielded_to_example
end

[false, nil].each do |falsy_value|
context "with a value of #{falsy_value.inspect}" do
it "is evaluated once per example" do
Expand Down Expand Up @@ -184,6 +196,18 @@ def define_and_run_group
end

describe "with a name" do
it "yields the example in which it is eval'd" do
example_yielded_to_subject = nil
example_yielded_to_example = nil

group = ExampleGroup.describe
group.subject(:foo) { |e| example_yielded_to_subject = e }
group.example { |e| foo; example_yielded_to_example = e }
group.run

expect(example_yielded_to_subject).to eq example_yielded_to_example
end

it "defines a method that returns the memoized subject" do
list_value_1 = list_value_2 = subject_value_1 = subject_value_2 = nil

Expand Down Expand Up @@ -516,6 +540,15 @@ def count
expect(@nil_value_count).to eq(1)
end

let(:yield_the_example) do |example_yielded_to_let|
@example_yielded_to_let = example_yielded_to_let
end

it "yields the example" do |example_yielded_to_example|
yield_the_example
expect(@example_yielded_to_let).to equal example_yielded_to_example
end

let(:regex_with_capture) { %r[RegexWithCapture(\d)] }

it 'does not pass the block up the ancestor chain' do
Expand Down

0 comments on commit 4f3f66a

Please sign in to comment.