Ruby on Rails4 + Mongoid + RSpec

Tadashi Shigeoka ·  Mon, November 4, 2013

Ruby on Rails4 + Mongoid + RSpec の環境構築メモ。

gem install rails --version 4.0.1
rails new myapp --skip-active-record --skip-test-unit
cd myapp
# Gemfile
gem 'mongoid', git: 'https://github.com/mongoid/mongoid.git'
rails g mongoid:config
      create  config/mongoid.yml
rails g rspec:install
% git diff
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 943bc19..9b7b0ef 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -13,6 +13,19 @@ Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
 ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
 
 RSpec.configure do |config|
+  ## Mongoid
+  config.before(:suite) do
+    DatabaseCleaner[:mongoid].strategy = :truncation
+  end
+
+  config.before(:each) do
+    DatabaseCleaner[:mongoid].start
+  end
+
+  config.after(:each) do
+    DatabaseCleaner[:mongoid].clean
+  end
+
   # ## Mock Framework
   #
   # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
@@ -22,12 +35,12 @@ RSpec.configure do |config|
   # config.mock_with :rr
 
   # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
-  config.fixture_path = "#{::Rails.root}/spec/fixtures"
+  # config.fixture_path = "#{::Rails.root}/spec/fixtures"
 
   # If you're not using ActiveRecord, or you'd prefer not to run each of your
   # examples within a transaction, remove the following line or assign false
   # instead of true.
-  config.use_transactional_fixtures = true
+  # config.use_transactional_fixtures = true
 
   # If true, the base class of anonymous controllers will be inferred
   # automatically. This will be the default behavior in future versions of
diff --git a/config/application.rb b/config/application.rb
index 7c9e566..9694074 100644
--- a/config/application.rb
+++ b/config/application.rb
@@ -4,7 +4,7 @@ require File.expand_path('../boot', __FILE__)
 # require "active_record/railtie"
 require "action_controller/railtie"
 require "action_mailer/railtie"
-require "sprockets/railtie"
+# require "sprockets/railtie"
 # require "rails/test_unit/railtie"
 
 # Require the gems listed in Gemfile, including any gems
diff --git a/config/initializers/mongoid.rb b/config/initializers/mongoid.rb
new file mode 100644
index 0000000..e400231
--- /dev/null
+++ b/config/initializers/mongoid.rb
@@ -0,0 +1 @@
+Mongoid.load!(Rails.root.to_s + "/config/mongoid.yml")

参考情報

Mongoid: Installation

Getting Started Rails 4 with MongoDB | Just Some More Dev Ideas

Using Mongoid with Rspec

Mongoid: Installation [Configuration]