【问题标题】:Rails: How to ensure clean state for test database?Rails:如何确保测试数据库的干净状态?
【发布时间】:2015-08-15 20:11:10
【问题描述】:

请帮忙解决问题。

工厂:

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)?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2020-01-16
      • 2014-03-04
      • 2019-02-07
      相关资源
      最近更新 更多