我正在尝试使用 RSpec 设置 DatabaseCleaner 以确保我可以正确清理我创建的任何测试对象。如果我不使用 DatabaseCleaner,则以下测试通过。
但是,当我将 DatabaseCleaner 代码添加到我的spec_helper.rb
文件时,测试失败,如下所述。
include AuthHelper
describe BulkJobsController do
describe 'GET /bulk_jobs/:id' do
context 'with valid user' do
before do
login_as('someuser')
end
context 'and a job' do
before do
@job = create(:bulk_job_close_cases)
puts "Test - Bulk Job Count: #{BulkJob.count}" # This is always 1
get :show, id: @job.id, format: 'json'
end
it 'is valid' do
response.status.should eq(200)
end
end
end
end
end
这是控制器:
class BulkJobsController < ApiController
def show
puts "Controller - Bulk Job Count: #{BulkJob.count}" # This is 1 without DC and 0 with DC
@job = BulkJob.find(params[:id])
respond_with @job
end
end
这是我spec/spec_helper.rb
文件的相关部分:
####################
# Database Cleanup #
####################
require 'database_cleaner'
config.use_transactional_fixtures = false
config.after(:suite) do
ActiveRecord::Base.connection.execute("DEALLOCATE ALL")
end
config.around(:each) do |example|
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.start
example.run
DatabaseCleaner.clean
end
奇怪的是,删除DatabaseCleaner.clean
语句实际上也不会使测试通过。但是,删除DatabaseCleaner.start
代码确实会使测试通过。
测试失败,因为控制器找不到具有正确 ID 的 BulkJob。如果我打印出对象的计数,则在测试中 BulkJobs 的数量为 1,但在控制器内部,它为 0。当测试通过时,显然,两个点的数字都是 1。
我没有包括 Capybara 或 Selenium,所以据我了解,rspec 应该使用 rack-test 来运行这个示例。
我的配置/测试有问题吗?DatabaseCleaner 清理太早了吗?
这是失败的测试:
Failures:
1) BulkJobsController GET /bulk_jobs/:id with valid user and a job is valid
Failure/Error: get :show, id: @job.id, format: 'json'
ActiveRecord::RecordNotFound:
Couldn't find BulkJob with id=39
# ./app/controllers/bulk_jobs_controller.rb:6:in `show'
# ./spec/controllers/bulk_jobs_spec.rb:33:in `block (5 levels) in <top (required)>'
和我的 Gemfile:
source 'http://rubygems.org'
gem 'rails', '~>3.2.12'
gem 'composite_primary_keys', '>=3.1.0'
gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'pg'
gem 'activerecord-mysql2-adapter', '~> 0.0.3'
gem 'rake', '>=0.8.7'
gem 'dalli'
gem 'postmark-rails'
gem 'rb-readline'
gem 'statsmix'
gem 'daemons'
gem 'delayed_job_active_record'
gem 'whenever', :require => false
gem 'iron_worker'
gem 'statsmix'
gem 'exceptional'
#gem 'newrelic_rpm'
group :test do
gem 'database_cleaner'
gem 'rspec-rails'
gem 'shoulda-matchers'
gem 'factory_girl_rails'
end