How to do proper database testing (TDD) on Rails 3 using MongoDB and Mongoid

后端 未结 5 2098
轻奢々
轻奢々 2021-02-04 03:02

How would go about writing proper unit testing (and integration testing for that matter) using MongoDB through Mongoid on Rails ?

I am asking, because to the opposite of

5条回答
  •  长发绾君心
    2021-02-04 03:32

    Ok thanks to Kyle who pointed me in the right direction, I found out how to make it work.

    So basically the trick is to drop all your collections in mongodb for each test case that you will run. This is a bit radical, but it works. But keep in mind that you won't retain any data at all in you test db.

    Finally I found that link: http://adventuresincoding.com/2010/07/how-to-configure-cucumber-and-rspec-to-work-with-mongoid

    And basically what you need to do is simple:

    add a block in you spec_helper.rb:

    RSpec.configure do |config|
    
    # blabla other confs
    
      config.before :each do
        Mongoid.master.collections.select {|c| c.name !~ /system/ }.each(&:drop)
      end
    
    # blabla other confs
    
    end
    

    For Mongoid 3:

     Mongoid.default_session.collections.select {|c| c.name !~ /system/ }.each(&:drop
    

    This effectively kills all the collection within the db allowing you to run your tests fresh every time.

    Alex

提交回复
热议问题