Skip to content
Browse files

Beef up/clarified specs for #582.

Also refactored `its` a bit
  • Loading branch information...
1 parent 5b861bb commit 924f59ad1a89ecbff4e262a6591ddf1d2cf6e4e6 @dchelimsky dchelimsky committed Mar 17, 2012
Showing with 34 additions and 18 deletions.
  1. +14 −9 lib/rspec/core/subject.rb
  2. +20 −9 spec/rspec/core/subject_spec.rb
View
23 lib/rspec/core/subject.rb
@@ -67,6 +67,16 @@ def should_not(matcher=nil, message=nil)
end
rescue LoadError
end
+
+ def _attribute_chain(attribute)
+ attribute.to_s.split('.')
+ end
+
+ def _nested_attribute(subject, attribute)
+ _attribute_chain(attribute).inject(subject) do |subject, attr|
+ subject.send(attr)
+ end
+ end
end
module ExampleGroupMethods
@@ -122,16 +132,11 @@ def its(attribute, &block)
example do
self.class.class_eval do
define_method(:subject) do
- unless instance_variable_defined?(:@_subject)
- @_subject = if attribute.is_a?(Array)
- super()[*attribute]
- else
- attribute.to_s.split('.').inject(super()) do |target, method|
- target.send(method)
- end
- end
+ if defined?(@_subject)
+ @_subject
+ else
+ @_subject = Array === attribute ? super()[*attribute] : _nested_attribute(super(), attribute)
end
- @_subject
end
end
instance_eval(&block)
View
29 spec/rspec/core/subject_spec.rb
@@ -194,23 +194,34 @@ def subject; super().first; end
end
end
- context "memorize subject" do
+ context "with nil subject" do
subject do
Class.new do
def initialize
- @counter = 0
+ @counter = -1
+ end
+ def nil_if_first_time
+ @counter += 1
+ @counter == 0 ? nil : true
+ end
+ end.new
+ end
+ its(:nil_if_first_time) { should be(nil) }
+ end
+
+ context "with false subject" do
+ subject do
+ Class.new do
+ def initialize
+ @counter = -1
end
def false_if_first_time
- if @counter == 0
- @counter += 1
- false
- else
- true
- end
+ @counter += 1
+ @counter > 0
end
end.new
end
- its(:false_if_first_time) { should be_false }
+ its(:false_if_first_time) { should be(false) }
end
end
end

0 comments on commit 924f59a

Please sign in to comment.
Something went wrong with that request. Please try again.