DEV Community

Discussion on: Why Choose `let` Over instance variables in RSpec

Collapse
 
jeremyf profile image
Jeremy Friesen

One of my favorite things in RSpec is to consider how let, subject, describe, and context can help you create specs that "self-document" (as in the formatted out is quite nice). When done well, it means I don't need to write many of the it "something or other" (which can sometimes drift from the spec).

RSpec.describe User do
  describe "#registered?"
    let(:confirmation_status) { true }
    let(:user) { User.new(confirmation_status: confirmation_status) }
    subject(:method_call) { user.registered? }

    context "when no confirmation" do
      let(:confirmation_status) { false }

      it { is_expected.to be_falsey }
    end

    context "with confirmation" do
      let(:confirmation_status) { true }

      it { is_expected.to be_truthy }
    end
  end
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
software_writer profile image
Akshay Khot

Definitely! I like how the tests can be self-documenting and also that RSpec provides a way to print the outcomes in various formats so it reads like a specification document.

Collapse
 
gumatias profile image
Gustavo Matias

Curious on how you think about describe vs context. In simple terms, how you decide to use one vs the other in different scenarios?

Collapse
 
jeremyf profile image
Jeremy Friesen

I choose "describe" for the thing under test (e.g. describe "#call"). And "context" for the conditionals (e.g. context "when given user is logged in").

Collapse
 
dylanlacey profile image
Dylan Lacey

I've always liked this, too! It's one of the reasons I find other testing tools so ... unpleasant.

Especially when there's lots of syntactical punctuation littered around.