Module: Shoulda::InstanceMethods
- Included in:
- Test::Unit::TestCase
- Defined in:
- lib/shoulda/context.rb
Instance Method Summary collapse
-
#get_instance_of(object_or_klass) ⇒ Object
:nodoc:.
-
#instance_variable_name_for(klass) ⇒ Object
:nodoc:.
-
#subject ⇒ Object
Returns an instance of the class under test.
-
#subject_block ⇒ Object
:nodoc:.
Instance Method Details
#get_instance_of(object_or_klass) ⇒ Object
:nodoc:
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'lib/shoulda/context.rb', line 244 def get_instance_of(object_or_klass) # :nodoc: if object_or_klass.is_a?(Class) klass = object_or_klass ivar = "@#{instance_variable_name_for(klass)}" if instance = instance_variable_get(ivar) warn "[WARNING] Using #{ivar} as the subject. Future versions " << "of Shoulda will require an explicit subject using the " << "subject class method. Add this after your setup to avoid " << "this warning: subject { #{ivar} }" instance else klass.new end else object_or_klass end end |
#instance_variable_name_for(klass) ⇒ Object
:nodoc:
262 263 264 |
# File 'lib/shoulda/context.rb', line 262 def instance_variable_name_for(klass) # :nodoc: klass.to_s.split('::').last.underscore end |
#subject ⇒ Object
Returns an instance of the class under test.
class UserTest
should "be a user" do
assert_kind_of User, subject # passes
end
end
The subject can be explicitly set using the subject class method:
class UserTest
subject { User.first }
should "be an existing user" do
assert !subject.new_record? # uses the first user
end
end
If an instance variable exists named after the described class, that instance variable will be used as the subject. This behavior is deprecated, and will be removed in a future version of Shoulda. The recommended approach for using a different subject is to use the subject class method.
class UserTest
should "be the existing user" do
@user = User.new
assert_equal @user, subject # passes
end
end
The subject is used by all macros that require an instance of the class being tested.
232 233 234 235 236 237 238 |
# File 'lib/shoulda/context.rb', line 232 def subject if subject_block instance_eval(&subject_block) else get_instance_of(self.class.described_type) end end |
#subject_block ⇒ Object
:nodoc:
240 241 242 |
# File 'lib/shoulda/context.rb', line 240 def subject_block # :nodoc: (@shoulda_context && @shoulda_context.subject_block) || self.class.subject_block end |