Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: implicitly defined subject

Rspec implicitly defined subject documentation says:

While the examples below demonstrate how subject can be used as a user-facing concept, we recommend that you reserve it for support of custom matchers and/or extension libraries that hide its use from examples.

Does it mean, that I should try to never call "subject." directly in my specs? If yes, what should I use instead as a subject object?

like image 366
krn Avatar asked Feb 03 '26 07:02

krn


1 Answers

Compare these 2 examples:

describe "User" do
  subject { User.new(age: 42) }
  specify { subject.age.should == 42 }
  its(:age) { should == 42 }
end

describe "User" do
  let(:user) { User.new(age: 42) }
  specify { user.age.should == 42 }
end

UPDATE

There is a cool feature in Rspec - named subject:

Here is an example from David Chelimsky:

describe CheckingAccount, "with a non-zero starting balance" do
  subject(:account) { CheckingAccount.new(Money.new(50, :USD)) }
  it { should_not be_overdrawn }
  it "has a balance equal to the starting balance" do
    account.balance.should eq(Money.new(50, :USD))
  end
end

When you use user instead of a subject it's more readable (IMHO). But subject lets you use nice extension its(:age).

like image 131
cutalion Avatar answered Feb 05 '26 21:02

cutalion