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

Commit c83eaf9

Browse files
committed
Named subject can be referred from an inside subject block
Example: describe "list" do subject(:list) { [1,2,3] } describe 'first' do subject(:first_element) { list.first } it { should eq(1) } end end With the previous implementation, this fails with "stack level too deep". This error is not obvious and irritating to me. I believe this behaviour is more natural.
1 parent f1ef071 commit c83eaf9

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

lib/rspec/core/subject.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,8 +193,12 @@ def its(attribute, &block)
193193
# @see ExampleMethods#subject
194194
# @see ExampleMethods#should
195195
def subject(name=nil, &block)
196-
define_method(name) { subject } if name
197-
block ? @explicit_subject_block = block : explicit_subject || implicit_subject
196+
if name
197+
let(name, &block)
198+
subject { instance_eval(name.to_s) }
199+
else
200+
block ? @explicit_subject_block = block : explicit_subject || implicit_subject
201+
end
198202
end
199203

200204
attr_reader :explicit_subject_block

spec/rspec/core/subject_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,17 @@ module RSpec::Core
9191
end
9292
group.run.should be_true
9393
end
94+
95+
it "is referred from inside subject by the name" do
96+
group = ExampleGroup.describe do
97+
subject(:list) { [1,2,3] }
98+
describe 'first' do
99+
subject(:first_element) { list.first }
100+
it { should eq(1) }
101+
end
102+
end
103+
group.run.should be_true
104+
end
94105
end
95106
end
96107

0 commit comments

Comments
 (0)