我有一个 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