2

I am working on creating a new Gem that has some models which use Mongoid. I would like to test my gem using RSpec. I have started using RSpec for writing tests. I have installed a gem called mongoid-rspec and set it up according to its documentation.

Now I need to tell Mongoid how to configure itself. Running rspec from the command line, it's now telling me that it couldn't find a mongoid.yml file and that I should run rails g mongoid:config. Obviously this won't work since I am testing a gem.

I'm new to rspec and mongoid, so I'm not quite sure of all the things I need to do to configure it properly in this test environment. It might be as easy as creating this mongoid.yml file, but I'm not sure of the best place to put it.

Any help would be appreciated. Thanks!

Andrew
  • 227,796
  • 193
  • 515
  • 708

2 Answers2

3

Here is how you can make Mongoid work in the context of a gem rspec test.

Setup a Mongoid configuration file under spec/config/mongoid.yml for example.

development:
  sessions:
    default:
      database: your_gem_db
      hosts:
        - localhost:27017

in your spec/spec_helper.rb file you can add

Mongoid.load!('./spec/config/mongoid.yml')

Please find further details about this issue on the Mongoid setup Documentation page

Quentin
  • 1,854
  • 1
  • 19
  • 19
1

Just add the following snippet to spec_helper config section:

# Clean up all collections before each spec runs.
config.before do
  Mongoid.purge!
end

This will clear mongo database before each test. Also you can use factory_girl (it works fine with Mongoid) and very helpful mongoid-rspec gem: https://github.com/evansagge/mongoid-rspec

..and basically that's it ;)

luacassus
  • 6,540
  • 2
  • 40
  • 58
  • 1
    This answer is unrelated to the question. – Quentin Feb 06 '14 at 20:39
  • I had some really strange issues (I think the database was persisting by default), and this answer (the purge part) really helped me out, and it was the first to show up on Google for me when I tried searching for my issue, so thanks. – Omar Bahareth Mar 13 '17 at 10:38