ruby.social is one of the many independent Mastodon servers you can use to participate in the fediverse.
If you are interested in the Ruby programming language, come join us! Tell us about yourself when signing up. If you just want to join Mastodon, another server will be a better place for you.

Administered by:

Server stats:

1.1K
active users

rspec users.. how do _you_ explain the difference between `subject` and `let`?

Esparta :ruby:

@kerrizor both are kind of the same, but IMO it's about semantics.

- `subject` is related to point and to name the system under test.
- `let` is related to making available a value to the context.

You can use both to perform the expectations, but semantically it is more "natural" to use the subject.

One difference is about when they are evaluated: all the `subject` are lazily evaluated, and some `let` can be _immediate_ if use `let!`

@kerrizor ... cont ...

re:

> rspec users.. how do _you_ explain the difference between `subject` and `let`?

Another difference: `subject` can be (ab)used to perform one-liners on expectations:

subject { Validator.call(obj) }

context 'with valid obj' do
let (:obj) { 42 }
it { is_expected.to be_valid }
end

context 'with invalid obj' do
let(:obj) { 18 }
it { is_expected.to be_failure }
end

@esparta subject can be eagerly evaluated as well with subject! (Same as let!)

@jasonkarns ohh right!

True. True.

Forgot about that, perhaps since I never use `subject!` and actually never seen in the codebases I've been working on.

@esparta agree. seeing it actually used would probably be a sign of a code smell if the subject needed to be triggered prior to example actually running 😬