Ruby on Rails: Adding Factory Girl steps to Turnip

Recently I've been trying out Turnip as an alternative to Cucumber. Turnip lets you run Gherkin tests inside RSpec. When using Factory Girl, the provided step definitions can be a huge help when setting up the preconditions for a scenario. Those step definitions do not work with Turnip due to differences from Cucumber in how Turnip defines steps. It turns out that it is very easy to convert the step definitions that Factory Girl can create into step definitions that Turnip can understand.

Factory Girl defines a function "convert_human_hash_to_attribute_hash" to process the Gherkin table steps. This needs to be available to RSpec examples as Turnip creates them from your Gherkin scenarios. So start by creating a file "spec/support/factory_girl_step_helpers.rb" and add "config.include FactoryGirlStepHelpers" in your "RSpec.configure" block. The contents of the file are in this gist. I have not needed to modify this module from the one that in the default Factory Girl step definition file.

The step definitions themselves require more significant modification. Lets look at how they are defined for Cucumber:

Given /^an? #{human_name} exists$/i do
  FactoryGirl.create(factory.name)
end

The conversion of this one into a Turnip step is straightforward:

step "a(n) #{human_name} exists" do
  FactoryGirl.create(factory.name)
end

The steps that handle a table with both the pluralized and singular versions is more complicated. The Cucumber step definition is:

Given /^the following (?:#{human_name}|#{human_name.pluralize}) exists?:?$/i do |table|
  table.hashes.each do |human_hash|
    attributes = convert_human_hash_to_attribute_hash(human_hash, factory.associations)
    FactoryGirl.create(factory.name, attributes)
  end
end

Initially I tried to use Turnip's ability to figure out "is/are" and "exist(s)" which looked like:

step "the following #{human_name}/#{human_name.pluralize} exist(s):" do |table|
  table.hashes.each do |human_hash|
    attributes = convert_human_hash_to_attribute_hash(human_hash, factory.associations)
    FactoryGirl.create(factory.name, attributes)
  end
end

This didn't work, it caused the table that was passed to the block to not be correct.
The only solution was to create 2 different step definitions, one for pluralized form and one for the singular form.

The final file that creates the step definitions for every defined factory is listed in this gist.
Simply place this file in "spec/acceptance/steps"

Now you can easily use steps like:

Given 20 things exist
  Given the following things exist:
    | name |
    | Ruby |
    | Rails |
    | Blog |

Now enjoy easily setting up your test database using your factories from within your Turnip feature files!

Check out our other articles about Ruby on Rails:

Setting Up Ubuntu 9.10 for Ruby on Rails Development

Multithreading on Ruby on Rails