What is the output of this Ruby RSpec code snippet?
RSpec.describe 'Example' do let(:number) { 5 } before do @result = number * 2 end it 'calculates result' do puts @result end end
Remember that let defines a memoized helper method accessible in before blocks.
The let(:number) defines a method returning 5. The before block runs before the test and sets @result to number * 2, which is 10. The test prints 10.
Which statement about let variables and before hooks in RSpec is true?
Think about when let variables get evaluated.
let variables are lazily evaluated the first time they are called. Since before hooks run before it blocks, accessing a let variable inside a before hook triggers its evaluation.
What will be printed when running this RSpec test?
RSpec.describe 'Multiple before hooks' do let(:counter) { @count ||= 0; @count += 1 } before do counter end before do counter end it 'prints counter value' do puts counter end end
Remember that let is memoized per example and evaluated once.
The let(:counter) is evaluated once per example. The first before calls it, setting @count to 1. The second before calls it again but uses the memoized value 1. The it block prints 1.
What will this RSpec code produce?
RSpec.describe 'Error example' do before do @value = number * 3 end let(:number) { 4 } it 'prints value' do puts @value end end
In RSpec, declaration order of let and before does not affect method availability.
In RSpec, let(:number) defines the method during the describe block evaluation, before examples or hooks run. Thus, number is available in the before block, @value is set to 12, and the test prints 12 with no error.
Given this RSpec code, what is the final value of @total printed?
RSpec.describe 'Complex let and before' do let(:base) { 10 } before do @total = base + 5 end before do @total += base end it 'prints total' do puts @total end end
Think about how let is evaluated and how @total changes in each before block.
The first before sets @total = base + 5 → 15. The second before adds base again → 15 + 10 = 25. The test prints 25.