gpt4 book ai didi

ruby-on-rails - rails : How do I ensure that the db reverts to its original state after tests?

转载 作者:行者123 更新时间:2023-11-28 21:22:50 24 4
gpt4 key购买 nike

我正在尝试编写一个涉及创建新用户的测试。但是,除了第一次之外,测试都失败了,因为用户在初始运行后永久保留在数据库中。

require 'test_helper'
require 'minitest/autorun'

describe UserMailer < ActionMailer::TestCase do
it 'will send an email when a new user is created' do
original_mail_count = ActionMailer::Base.deliveries.count
User.create(email: "new_user@test.com", password: "password").save
ActionMailer::Base.deliveries.count.must_equal original_mail_count + 1
end
end

如何确保数据库在测试运行后恢复到测试前的状态?

最佳答案

使用database_cleaner gem

示例用法:

# spec_helper.rb
RSpec.configure do |config|
config.before(:each) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end

关于ruby-on-rails - rails : How do I ensure that the db reverts to its original state after tests?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47580939/

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