Setting up RSpec and Factory girl
Not another RSpec tutorial! I know, there’s plenty of well written tutorials out there. But, thankfully, this is only a cheat sheet. The article below outlines the steps to get RSpec and Factory girl set up in your Rails app. If you want a TL;DR, follow the code snippets and skip all the text.
This will generate a
spec/ folder inside your application. You can remove the
test/ folder if it exists.
Next create the file
spec/support/factory_girl.rb and paste in:
This makes method calls less verbose. For example instead of
FactoryGirl.build you can now use
Next, uncomment the following line in
spec/rails_helper.rb to autoload files in the
Everything is now setup. The next step is to generate a test and create a factory. Then we need to make sure everything passes.
Generating a test and running it
An RSpec test will be generated whenever you generate a model or controller. RSpec also offers generators to generate a test only. For example here’s how to generate a test for the model, Widget.
Check the RSpec documentation on generators to learn more.
Fun fact: with Factory Girl installed, a factory will also be generated when you generate a test.
Here are the files created when running the above RSpec generator. This should also generate a Factory Girl file
To run the test:
✅ RSpec + Factory Girl installation
This was originally posted on Medium.