测试类方法时,我不需要自动创建实例。隐式主题是自动创建的,还是仅在引用时创建的?
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
答案 0 :(得分:3)
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
那些规格通过,证明它是懒惰的。