Boldr by N. Merouze

Easy Testing MongoMapper models

There’s a bunch of libraries to write tests easily for your app. factory_girl and Machinist for the fixtures. Remarkable for the macros.

There’s no core support for MongoMapper in any of these solutions but Machinist and Remarkable are agnostic so it’s easy to add a MongoMapper support. That’s what I did a few months ago with machinist_mongo and remarkable_mongo.

I’m refactoring them to add Mongoid support in a near future and I think it’s time to have a bit of docs on these 2 gems. Let’s see how to use them in a Rails project with RSpec.

Machinist for MongoMapper

First we load the gem:

Then it’s like any other Machinist adapter. We create the blueprint:

We require the blueprints.rb file into spec_helper.rb:

We write the specs:

And finally the related model:

Like Machinist for ActiveRecord you have the 3 following methods: Model.make, Model.make_unsaved, Model.plan. And there’s a preliminary support for embedded documents.

Remarkable for MongoMapper

The first step is the same that Machinist, requiring the gems:

Let’s add the specs. Say we want to check the existence of title and body keys and the title presence validation:

Finally we modify the model to pass the specs:

Remarkable for MongoMapper is not feature complete (as of v0.1.2). Here’s the list of macros but they don’t support all the options of the related MongoMapper methods.

  • belong_to
  • have_many
  • have_key/have_keys
  • validate_presence_of
  • validate_confirmation_of
  • validate_length_of (bugged)
  • allow_values_for

If you want to add features, fork the repo.

Conclusion

If you’ve already used Machinist and/or Remarkable you won’t have problems. For the other ones it is an easy solution to write your tests quickly.