Using Mongoid with Rspec

I'm a fan of testing. I'm still trying to discipline myself to test before I write code, that's been a tough habit to develop, however testing after I develop a feature is a good habit that has paid dividends. Lately I've started learning how to use Rspec for Rails.

Out of the box, Rspec is configured to use ActiveRecord. I've pretty much stopped using relational databases in favor of NoSql solutions. My favorite NoSql DB is MongoDB. The Ruby MongoDB ORM that I've been using is Mongoid.

To prep for Rspec, make your gemfile look like this (Assuming Rails 3.x):

gem 'rspec-rails', :group => [:test, :development]
group :test do
  gem 'database_cleaner'

Then run: bundle install rails g rspec:install

When I started learning how to use Rspec, I started having problems. The first was the following error message:

undefined method `fixture_path=' for # (NoMethodError)

Oops, just needed to comment out the line spec_helper.rb:

config.fixture_path = "#{::Rails.root}/spec/fixtures"

Was I safe yet? Nope. Another error: undefined method `use_transactional_fixtures=' for # (NoMethodError)

Oops, just needed to comment out the line spec_helper.rb:

config.use_transactional_fixtures = true

I should have known as the there are comments in the file.

Now, when I run my specs, the changes to the database persist from one test to the next. Ideally, you want a clean database when you start each test. This is where the gem database_cleaner comes in handy.

Then add this to your spec_helper.rb file:

  config.before(:suite) do
    DatabaseCleaner[:mongoid].strategy = :truncation

  config.before(:each) do

  config.after(:each) do

That's it!

If you made it this far, you should follow me on Twitter.


Want to test-drive Bitcoin without any risk? Check out my bitcoin wallet Coinbolt. It includes test coins for free.

comments powered by Disqus