RSpec 懒惰的主题 [英] RSpec lazy subject

查看:30
本文介绍了RSpec 懒惰的主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When testing class methods, I don't need an instance to be created automatically. Is an implicit subject created automatically, or only when referenced?

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 appears to be a method which creates the object necessary and returns it. So it would only create a subject object when called.

虽然测试自己很容易...

It's easy enough to test yourself though...

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

那些规范通过了,证明它很懒.

Those specs pass, proving that it's lazy.

这篇关于RSpec 懒惰的主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆