Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec lazy subject

Tags:

ruby

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
like image 821
Andrew Avatar asked Dec 30 '25 18:12

Andrew


1 Answers

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.

like image 111
Alex Wayne Avatar answered Jan 02 '26 12:01

Alex Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!