我正在尝试使用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