Introduction
Let and before hooks help you set up values and actions before running tests. They keep your tests clean and avoid repeating code.
Let and before hooks help you set up values and actions before running tests. They keep your tests clean and avoid repeating code.
let(:name) { value }
before do
# setup code here
endlet defines a value that is created only when needed.
before runs code before each test example.
number to 5 when used, and prints a message before each test.let(:number) { 5 }
before do
puts "Starting test"
end@name before tests.let(:greeting) { "Hello" }
before do
@name = "Alice"
endThis test shows how let creates a number and before sets a doubled value before each test.
require 'rspec' RSpec.describe 'Let and before example' do let(:number) { 10 } before do @double = number * 2 end it 'uses let to get number' do expect(number).to eq(10) end it 'uses before to set double' do expect(@double).to eq(20) end end # To run this test, save as example_spec.rb and run: rspec example_spec.rb
let values are lazy and memoized, so they run only once per test when called.
before hooks run before every test example, so use them for setup tasks.
let creates reusable values for tests.
before runs setup code before each test.
Both help keep tests clean and avoid repeating code.
let in Ruby tests?let behaviorlet defines a value that is created only when needed (lazy evaluation) and reused within the same test.beforebefore runs code before each test but does not create reusable values like let.let = reusable lazy value [OK]let variable named user with value "Alice"?let syntaxlet takes a symbol argument and a block returning the value: let(:name) { value }.before, not let.let syntax uses symbol and block [OK]let(:count) { 0 }
before { count += 1 }
it "increments count" do
puts count
endlet and before interactionlet(:count) { 0 } defines a method returning 0. But count is not a variable; it's a method call.before { count += 1 }count += 1 tries to modify count as a variable, but count is a method, so Ruby raises an error: undefined method += for nil or no local variable.let(:numbers) { [1, 2, 3] }
before do
numbers << 4
end
it "checks numbers length" do
expect(numbers.length).to eq(4)
endlet(:numbers) memoizes a new array [1,2,3] the first time numbers is called in each test example.before, numbers << 4 calls/memoizes numbers and mutates it to [1,2,3,4]. In it, numbers.length (memoized) is 4, so test passes.before(:each) affects per-example memoized let correctly [OK]before(:each) with before(:all)let and before hooks?let(:user_name) { "Bob" }
before do
@user = User.new(name: user_name)
@user.activate!
end
it "checks user is active" do
expect(@user.active?).to be true
endlet(:user_name) defines reusable data lazily, while before runs setup code creating and activating user.user_name) from setup actions (before) -> Option APass the test and this pattern moves unknown