Rails: 如何确保测试数据库处于干净状态?

Rails: How to ensure clean state for test database?

请帮忙解决问题

工厂:

FactoryGirl.define do
  factory :album do
    sequence(:title){ |i| "title#{i}" }
    user_id 1
    closed nil
    description 'g dgd fghf ghj gj gj gj gj g'
  end
end

albums_controller_spec.rb:

require 'spec_helper'
describe AlbumsController, type: :controller do
  describe 'show action' do
    it 'render show template if user and album is found' do
      album = FactoryGirl.create(:album)
      get :show, { user_id: 1, id: album.id }
      response.should render_template('show')
      response.should render_template "layouts/application"
    end
  end  
end

专辑型号:

class Album < ActiveRecord::Base
  validates :title, presence: true, length: { maximum:  50, minimum: 3 }, uniqueness: { case_sensitive: false }
  validates :description, presence: true, length: { maximum:  600, minimum: 10 }

  belongs_to :user
  has_many :images
end

i 运行 在控制台中:

rspec spec

控制台显示如下:

OK
Finished in 0.28618 seconds (files took 1.91 seconds to load)
1 example, 0 failures

但我再次运行命令:

rspec spec

并且控制台显示错误信息:

ERROR: record is exist!
rspec ./spec/controllers/albums_controller_spec.rb:14 # AlbumsController show action render show template if user and album is found

那个没有错误,我每次都要运行:

rake db:reset RAILS_ENV=test

但是很不方便。请告诉我,是否可以不每次都输入此命令(db:reset)?

您可以使用 database_cleaner gem 来确保测试的干净状态。

您可以这样配置 RSpec:

RSpec.configure do |config|

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

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

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

然后,您将能够 运行 您只需使用 rspec spec 命令即可实现规范,而无需每次都手动重置数据库。