//
you're reading...
Cucumber, MongoDB

Factory Girl associations with MongoMapper

If you have an association (an Article belonging to a User) and you write something like that in Cucumber:

Given the following article exists:
 | title      | user                       |
 | My article | email: writer1@example.com |

then the Factory Girl steps will handle this association for you, creating both an Article and a User for your test if they are of the ActiveRecord class. But this will throw an exception with MongoMapper.

Digging into the Factory Girl steps code explains why. Factory Girl steps use User.find(:first, :conditions => attributes) but syntax such as find(:first…) doesn’t exist for MongoMapper.
MongoMapper uses Plucky gem for all the find methods. I wrote the following monkey patch to account for the missing attributes:
/config/initializers/plucky_ext.rb
----------------------------------

Plucky::Query.class_eval do
alias_method :find_old, :find
def find_new(*args)
  options = args.extract_options!
  first = args.shift
  args.push(options)

  case first
     when :first
       first(*args)
     when :last
       last(*args)
     when :all
       all(*args)
     else
       args.unshift(first) unless first.nil?
       find_old(*args)
  end
end
alias_method :find, :find_new
end

Now the Factory Girl steps work with associations

Advertisements

About RailsBlogger

I'm a Software Developer with over 10 years of experience, Java and Ruby on Rails.

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: