boldr by Nicolas Mérouze

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:

config.gem "machinist_mongo", :lib => "machinist/mongo_mapper"

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

Post.blueprint do
  title "I like MongoDB!"
  body "I have a ton of reasons for that."
end

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

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
require 'spec/autorun'
require 'spec/rails'
require 'spec/blueprints'

Spec::Runner.configure do |config|
end

We write the specs:

require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Post do
  before(:all) do
    @post = Post.make
  end

  it "should have a title" do
    @post.title.should == "I like MongoDB!"
  end
end

And finally the related model:

class Post
  include MongoMapper::Document

  key :title, String
  key :body, String
end

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:

config.gem "remarkable_rails", :lib => "remarkable_rails"
config.gem "remarkable_mongo", :lib => "remarkable/mongo_mapper"

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

require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Post do
  it { should have_keys(:title, :body, String) }
  it { should validate_presence_of(:title) }
  # ...
end

Finally we modify the model to pass the specs:

class Post
  # ...
  validates_presence_of :title
end

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.

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.

If you liked the article and/or want to talk to me about it, you can follow me on twitter.