[英]Clean out, or reset test-database with Rspec and Mongoid 5.0 on Rails 4
[英]Rspec - How to clean the database after each test
我有一个功能规格与Capybara的登录页面,我正在使用FactoryGirl + DatabaseCleaner
require 'rails_helper'
feature 'Admin signs in' do
background do
FactoryGirl.create(:user)
end
scenario 'with valid credentials' do
visit admin_root_path
fill_in 'user_email', :with => 'email@email.com'
fill_in 'user_password', :with => 'testpassword'
click_button 'Sign in'
expect(page).to have_content('Dashboard')
end
scenario 'with invalid credentials' do
visit admin_root_path
fill_in 'user_email', :with => 'email@email.com'
fill_in 'user_password', :with => 'wrongpassword'
click_button 'Sign in'
expect(page).to have_content('Admin Login')
end
end
运行测试,我收到以下错误:
1) Admin signs in test with invalid credentials
Failure/Error: FactoryGirl.create(:user)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken
我认为DatabaseCleaner会恢复更改,但看起来用户记录在数据库中持续存在直到第二个场景块。
如何在第一个场景后确保清理数据库?
我在此帖后配置了数据库清理程序
# support/database_cleaner_spec.rb
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
我还更新了规范帮助文件:
config.use_transactional_fixtures = false
我错误地认为spec / support文件夹中的配置文件是自动加载的,但事实证明我必须取消注释spec / rails_helper.rb中的以下行
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
DatabaseCleaner配置文件是正确的,它根本没有加载。
确保在spec / rails_helper.rb中具有以下配置
RSpec.configure do |config|
config.use_transactional_fixtures = true
end
我们的想法是使用干净的数据库启动每个示例,创建该示例所需的任何数据,然后通过简单地回滚示例末尾的事务来删除该数据。
使用这些设置:
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
如果您在测试中的方法中使用MySQL并更改表(重置自动增量或任何DDL操作),则事务策略将失败并且您的数据库将不会被清除。
为了修复,你必须声明一个这样的配置块:
config.before(:each, :altering_database => true) do
DatabaseCleaner.strategy = :truncation
end
并将此配置添加到您的测试上下文:
context "when you alter the DB", :altering_database => true do...
注意:这会降低您的测试速度,因此请注意不要滥用它。
config.before(:example) do
DatabaseCleaner.clean_with(:truncation)
end
为我工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.