gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:47:41 24 4
gpt4 key购买 nike

请帮忙解决问题。

工厂:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com