Last active
December 6, 2022 10:35
-
-
Save reggieb/3f9b597a896a24fdf171cb785c3e7f9d to your computer and use it in GitHub Desktop.
Use fixtures along side FactoryBot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FixtureError = Class.new(StandardError) | |
# | |
# Wrapper for fixtures so they can be loaded with a FactoryBot type syntax | |
# Usage: | |
# fixture :user, :admin | |
# | |
# This will try to find a model with an id that matches the fixture label | |
def fixture(model_name, label) | |
model = model_name.to_s.classify.constantize | |
id = ActiveRecord::FixtureSet.identify(label) | |
model.find(id) | |
rescue ActiveRecord::RecordNotFound | |
raise FixtureError, "#{label} fixture not found for #{model_name}" | |
rescue NameError | |
raise FixtureError, "No class found for #{model_name}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Background
Recently I've been working on a project when fixtures were used instead of factories, to greatly reduce the running time for specs.
I think both fixtures and factories have their advantages and disadvantage. So I wondered if it is possible to use both in a project.
Usage
Adding this gist code to
rspec/support/fixture.rb
allows fixtures to be used with a similar syntax to factories.Example
So in a rails project with FactoryBot installed the following is possible: