A better before block setup in RSpec?

I prefer option 2. There are a few ways you can improve it:

  • If the @user variable isn’t used outside of the before block then you can use a local variable instead.
  • If the user’s name isn’t important for the test, consider setting first_name and last_name in the factory instead. And similarly with tail_length.
  • If you define a kite association in the tail factory, it will be created automatically. (Sometimes this feature is overused and make tests hard to understand, so use your judgement.)
  • You could use create_list and create_pair as a shorthand for creating multiple records.

So you could potentially reduce the whole block to something like:

before do
  user = create(:user)
  create_pair(:tail, user: user)
end
1 Like