22

I included database_cleaner gem in my rails app. Followed the example given on the git repo and included the following code in spec_helper :

Approach 1

  config.before(:suite) do
   DatabaseCleaner.strategy = :transaction
   DatabaseCleaner.clean_with(:truncation)
  end

  config.around(:each) do |example|
   DatabaseCleaner.cleaning do
    example.run
   end
  end

When i run the rspec i get error as NoMethodError:undefined method 'cleaning' for DatabaseCleaner:Module.

So i did some research and found that i could replace the config.around block above with something like this :

Approach 2

config.before(:each) do
 DatabaseCleaner.start
end

config.after(:each) do
 DatabaseCleaner.clean
end 

OR

Approach 3

config.around(:each) do |example|
  DatabaseCleaner.start
  example.run
  DatabaseCleaner.clean
end

Both Approach 2 and 3 work well.
I also looked in the git repo of database_cleaner and found that cleaning method actually exists and with the following code :

def cleaning(&block)
     start
     yield
     clean
   end

which is exactly same as what i did in example 3. If it does exists then why is it not accessible? Am i missing something here. Any more setup? Or is Approach 2 or 3 preferable?

4

3 回答 3

25

终于找到答案了

database_cleanergemcleaning上周刚刚添加了该方法,并更新了相同的文档。但我从 ruby​​gems.org 获取的最新 gem 版本 1.2.0 中没有此更改。Approach 1当我从以下来源获取宝石时,效果很好github

gem 'database_cleaner', git: 'git@github.com:DatabaseCleaner/database_cleaner.git'
于 2014-02-01T04:44:00.100 回答
1

You can use the approach in the documentation if you pull the gem from Github

gem 'database_cleaner', git: 'git@github.com:bmabey/database_cleaner.git'

于 2014-02-04T15:42:03.800 回答
-1

如果您在使用 mongoid 时遇到同样的问题,您可以将其添加到 Gemfile,更改版本以适合您,然后运行 ​​bundle install。

gem 'database_cleaner', '~> 1.4.1'

然后在中创建一个支持文件夹

spec/support/database_cleaner.rb

在您的 spec_helper 文件中需要 database_cleaner.rb,我gem 'require_all'这样使用:

# spec/spec_helper.rb
require 'require_all'

require_rel 'support'

将以下清理程序添加到 database_cleaner.rb

RSpec.configure do |config|

  # Cleanup the DB in between test runs
  config.before(:suite) do
    DatabaseCleaner[:mongoid].strategy = :truncation
    DatabaseCleaner[:mongoid].clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end

您的测试现在应该正确地拆除。

于 2015-04-13T06:41:38.017 回答