Fixtures in Ruby on Rails with RSpec

Gokul
2 min readJan 28, 2023

What?

Ruby on Rails fixtures are a way to provide test data for your application. Most of the time, you use them with the RSpec testing framework to give your tests test data. Fixtures are a way to pre-populate your test database with a set of data that you can use to test your application.

Fixtures are stored in files that have a .yml file extension and are located in the test/fixtures directory of your Rails application. These files use the YAML (YAML Ain't Markup Language) format, which is a human-readable data serialization format. Each file is linked to a specific table in the database, and the data in the file is linked to the rows that will be added to that table.

How?

Here’s an example of how you might use fixtures in a Ruby on Rails application:

Create a fixture file in the test/fixtures directory. For example, if you want to test a model called User, you would create a file called users.yml in the test/fixtures directory.

# test/fixtures/users.yml

joe:
first_name: Joe
last_name: Smith
email: joe@example.com
password: secret

susan:
first_name: Susan
last_name: Johnson
email: susan@example.com
password: supersecret

Create a test for the User model. For example, you might create a file called user_spec.rb in the spec/models directory.

# spec/models/user_spec.rb
require 'rails_helper'

describe User do
describe '#full_name' do
it 'returns the full name of the user' do
user = users(:joe)
expect(user.full_name).to eq 'Joe Smith'
end
end
end

Run the test using the rspec command.

$ rspec spec/models/user_spec.rb

The first time you run the test, the fixtures will be loaded into the test database. You can also load the fixtures into the test database using the command

rake db:fixtures:load

In the above example, the users(:joe) method is provided by ActiveRecord::FixtureSet and it returns the fixture data for the user named "joe". The users method returns all the fixtures for the user's table.

You can also use the transactions in Rspec to rollback the data after the test; this way, you don't need to clean the database after each test, but this can slow down your test suite.

It’s worth noting that as your application and test suite grow, it’s a good idea to use a library like FactoryBot, which helps you manage your fixtures in a more flexible and efficient way.

Additionally, you can use ActiveRecord to create your fixtures in code, by using the create or create! method provided by ActiveRecord. This allows you to programmatically generate test data.

If you enjoyed this article and want to support my writing, click this link to get notified whenever I publish something new.

If you’d like to support me more, click here. Happy Reading!!!

--

--

Gokul

Consultant | Freelancer | Ruby on Rails | ReactJS