DEV Community

Vasily Polovnyov
Vasily Polovnyov

Posted on

Rule of thumb: let vs. before

Sometimes I see code like this:

describe ".active" do
  let!(:active_accounts) { create_list(:active_account, 2) }
  before { create_list(:pending_account, 3) }

  it "returns only active accounts" do
    expect(described_class.active).to match_array(active_accounts)
  end
end
Enter fullscreen mode Exit fullscreen mode

This spec is a bit misleading. Why we create some dependencies in let and some in before? What is hidden here? What is the purpose of those accounts created in before? Usually the answer is this: we are not accessing inactive accounts in the test, so we don't need a variable, we just create them in before.

To make test clear, it is better to always stick to the rule: use let to create and specify dependencies, and before - to bring the system under test to the desired state:

describe ".active" do
  let!(:active_accounts) { create_list(:active_account, 2) }
  let!(:pending_accounts) { create_list(:pending_account, 3) }

  it "returns only active accounts" do
    expect(described_class.active).to match_array(active_accounts)
  end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)