Permalink
Browse files

Made #subject lazy so it only builds once

  • Loading branch information...
1 parent 78d5e4a commit 61f16a3588ed01661cebe89d8dd09dbc1580528d @zdennis zdennis committed with Joe Ferris Sep 19, 2009
Showing with 19 additions and 5 deletions.
  1. +11 −5 lib/shoulda/context.rb
  2. +8 −0 test/other/context_test.rb
@@ -230,11 +230,7 @@ module InstanceMethods
# The subject is used by all macros that require an instance of the class
# being tested.
def subject
- if subject_block
- instance_eval(&subject_block)
- else
- get_instance_of(self.class.described_type)
- end
+ @shoulda_subject ||= construct_subject
end
def subject_block # :nodoc:
@@ -262,6 +258,16 @@ def get_instance_of(object_or_klass) # :nodoc:
def instance_variable_name_for(klass) # :nodoc:
klass.to_s.split('::').last.underscore
end
+
+ private
+
+ def construct_subject
+ if subject_block
+ instance_eval(&subject_block)
+ else
+ get_instance_of(self.class.described_type)
+ end
+ end
end
class Context # :nodoc:
@@ -187,3 +187,11 @@ def setup
assert_equal @expected, subject
end
end
+
+class SubjectLazinessTest < ActiveSupport::TestCase
+ subject { Subject.new }
+
+ should "only build the subject once" do
+ assert_equal subject, subject
+ end
+end

0 comments on commit 61f16a3

Please sign in to comment.