DRY Up Your Factory Girl Factories With RSpec and Cucumber
When I first set up the fixture replacement gem Factory_Girl in my current Ruby on Rails project, I had two files with the same code in each one, creating the same factory twice. One in RSpec’s spec/factories directory, and another in Cucumber’s features/support directory. According to the Don’t Repeat Yourself (DRY) principle, this was not ideal. How to fix?
I asked the question in the #rspec channel on IRC, and lucky me, David Chelimisky, the lead developer/maintainer of RSpec, answered. Simply require the factory file from RSpec in Cucumber’s features/support/env.rb file. Like this:
require_relative("../../spec/factories/model_name.rb")
But this could get quite tedious, if you have more than one model. Which of course, you probably do. So, here’s a snippet that will load all of your factories:
Dir["../../spec/factories/*.rb"].each {|file| require_relative file }
I put this in my features/support/env.rb file. If you use Spork, I put it in my Spork.each_run section.
Are you using factory_girl, machinist, or another fixture replacement library? Let me know in the comments if you know a better way to do it.