Bird
0
0

What is wrong with this test code?

medium📝 Debug Q7 of 15
Ruby - Testing with RSpec and Minitest
What is wrong with this test code?
let(:array) { [] }
before { array << 1 }
it 'has one element' do
  expect(array.size).to eq(1)
end
it 'is empty initially' do
  expect(array).to eq([])
end
Alet does not allow modifying returned objects
Bbefore hook runs after the test examples
CThe array is shared and mutated across tests causing unexpected results
Darray is not defined in before hook
Step-by-Step Solution
Solution:
  1. Step 1: Understand let memoization and mutation

    let(:array) returns a new array instance per example, but mutation inside before affects that instance within the example.
  2. Step 2: Analyze test order and mutation effect

    Each test example gets a fresh array, but mutation in one example does not affect others. However, if the array is memoized and mutated in a shared context, it can cause unexpected results.
  3. Final Answer:

    The array is shared and mutated across tests causing unexpected results -> Option C
  4. Quick Check:

    Mutating let objects can cause shared state bugs if not careful [OK]
Quick Trick: Avoid mutating let objects to prevent shared state bugs [OK]
Common Mistakes:
  • Assuming let returns new object each time
  • Thinking before runs after tests
  • Ignoring mutation side effects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes