Using Rails Fixtures with RSpec

· 173 words · 1 minute read

After creating a new Rails 7 app, the test/test_helper.rb file looks like this:

ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

class ActiveSupport::TestCase
  # Run tests in parallel with specified workers
  parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

fixtures: all loads all fixtures once before the test cases. I think this is the only reasonable way of using fixtures.

If you wish to achieve the same with RSpec, you’ll need to add the following to spec/rails_helper.rb:

config.global_fixtures = :all

While it may seem logical to load fixtures within an example group like so:

describe Thing do
  fixtures :things

  it 'checks something' do
    expect(things(:one).name).to eq 'First'
  end
end

The problem with this approach is that fixtures will be loaded before the transaction of the example starts so they won’t be rolled back. This means that the created records will be leaked to the next example group, which is probably not the desired outcome.