From c83eaf9b7ad3400dec80ebccbdb9c646640e6899 Mon Sep 17 00:00:00 2001 From: tomykaira Date: Sat, 1 Sep 2012 17:42:11 +0900 Subject: [PATCH 1/2] 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. --- lib/rspec/core/subject.rb | 8 ++++++-- spec/rspec/core/subject_spec.rb | 11 +++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/rspec/core/subject.rb b/lib/rspec/core/subject.rb index 0dbdbcb9fc..079a406695 100644 --- a/lib/rspec/core/subject.rb +++ b/lib/rspec/core/subject.rb @@ -193,8 +193,12 @@ def its(attribute, &block) # @see ExampleMethods#subject # @see ExampleMethods#should def subject(name=nil, &block) - define_method(name) { subject } if name - block ? @explicit_subject_block = block : explicit_subject || implicit_subject + if name + let(name, &block) + subject { instance_eval(name.to_s) } + else + block ? @explicit_subject_block = block : explicit_subject || implicit_subject + end end attr_reader :explicit_subject_block diff --git a/spec/rspec/core/subject_spec.rb b/spec/rspec/core/subject_spec.rb index 140d67df6b..1c4a8bf9d0 100644 --- a/spec/rspec/core/subject_spec.rb +++ b/spec/rspec/core/subject_spec.rb @@ -91,6 +91,17 @@ module RSpec::Core end group.run.should be_true end + + it "is referred from inside subject by the name" do + group = ExampleGroup.describe do + subject(:list) { [1,2,3] } + describe 'first' do + subject(:first_element) { list.first } + it { should eq(1) } + end + end + group.run.should be_true + end end end From b31162779edb48cc5ded0458c6e2ca65cf3f93fb Mon Sep 17 00:00:00 2001 From: tomykaira Date: Sat, 1 Sep 2012 21:22:34 +0900 Subject: [PATCH 2/2] Use a simpler way to invoke a method by name --- lib/rspec/core/subject.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rspec/core/subject.rb b/lib/rspec/core/subject.rb index 079a406695..81a057bb46 100644 --- a/lib/rspec/core/subject.rb +++ b/lib/rspec/core/subject.rb @@ -195,7 +195,7 @@ def its(attribute, &block) def subject(name=nil, &block) if name let(name, &block) - subject { instance_eval(name.to_s) } + subject { send name } else block ? @explicit_subject_block = block : explicit_subject || implicit_subject end