ruby-on-rails - rails : How to ensure clean state for test database?

标签 ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 rspec

请帮忙解决问题。

工厂:

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

我在控制台中运行:

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 命令运行您的规范,而无需每次都手动重置数据库。

关于ruby-on-rails - rails : How to ensure clean state for test database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028909/

相关文章:

ruby-on-rails - 复杂的选择集,Rails 方式?

ruby-on-rails - ActionController::UnknownFormat 错误

JavaScript 挑战——Rails 按钮迭代

ruby-on-rails - 设计重定向到成功登录似乎卡在第一次登录尝试

ruby-on-rails - 如何在 Rails 3.1 中获取资源的绝对 URL?

ruby-on-rails - 如何配置 action mailer(我应该注册域)?

java - 使用 javac 在 Heroku 上运行 java 程序

ruby - 扩展 uniq 方法

ruby-on-rails - 在 Mac 操作系统上重置终端?帮助安装 Rails

javascript - Rails 3.2 - 文本字段更改时的 Ajax 调用