Repository navigation
Let example
Cyril Kato edited this page Nov 1, 2026
·
1 revision
let defines a private method of the group, called each time it is used. Its block takes parameters, a nested group may redefine it with super, and nothing is memoized: a helper that must give the same object twice keeps it in an instance variable.
require "r_spec"
RSpec.describe "a helper" do
let(:name) { "Bob" }
let(:greeting) { |word| "#{word}, #{name}!" }
it { expect(name).to eq "Bob" }
it { expect(greeting("Hello")).to eq "Hello, Bob!" }
context "with a last name" do
let(:name) { "#{super()} Smith" }
it { expect(greeting("Hi")).to eq "Hi, Bob Smith!" }
end
context "when called twice" do
let(:object) { [] }
it "gives a new object each time" do
expect(object).not_to be object
end
end
context "when memoized by hand" do
let(:object) { @object ||= [] }
it "gives the same object" do
expect(object).to be object
end
end
end$ ruby spec/let_spec.rb
spec/let_spec.rb:7: Success: expected "Bob" to eq "Bob"
spec/let_spec.rb:8: Success: expected "Hello, Bob!" to eq "Hello, Bob!"
spec/let_spec.rb:13: Success: expected "Hi, Bob Smith!" to eq "Hi, Bob Smith!"
spec/let_spec.rb:20: Success: expected [] not to be []
spec/let_spec.rb:28: Success: expected [] to be []