2

在测试类方法时,我不需要自动创建实例。隐式主题是自动创建的,还是仅在引用时创建?

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
4

1 回答 1

4

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

这些规格通过,证明它是懒惰的。

于 2013-07-16T23:45:59.303 回答