在测试类方法时,我不需要自动创建实例隐式主题是自动创建的,还是仅在引用时创建的?
describe MyClass do
it 'uses implicit subject' do
subject.my_method.should be_true
end
it 'does not create a subject' do
MyClass.works?.should be_true
# subject should not have been created
end
end
最佳答案
subject
似乎是一个创建所需对象并返回该对象的方法所以它只会在调用时创建一个subject对象。
但这很容易测试你自己。。。
class MyClass
cattr_accessor :initialized
def initialize
MyClass.initialized = true
end
def my_method
true
end
def self.works?
true
end
end
describe MyClass do
it 'uses implicit subject' do
MyClass.initialized = false
subject.my_method.should be_true
MyClass.initialized.should == true
end
it 'does not create a subject' do
MyClass.initialized = false
MyClass.works?.should be_true
MyClass.initialized.should == false
end
end
那些规格通过了,证明它很懒。