krn
krn

Reputation: 6815

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?

Upvotes: 3

Views: 608

Answers (1)

cutalion
cutalion

Reputation: 4394

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).

Upvotes: 3

Related Questions