gpt4 book ai didi

ruby-on-rails - 编写 Rails 测试,不要保留那么多数据库对象

转载 作者:行者123 更新时间:2023-11-28 21:13:09 26 4
gpt4 key购买 nike

我正在尝试重构一些 RSpec/Rails 测试,以便它们将尽可能少的对象保存到数据库中,但我在尝试弄清楚如何重写如下测试时遇到了麻烦:

describe User do
context "record creation" do
before(:each) { @user = User.new(user_atts) }

it "should generate a confirmation_token" do
# Generated as the result of a callback
@user.save!
expect(@user.confirmation_token).to be_present
end

it "should set the confirmed_at attribute to nil" do
# Cleared as the result of a callback
@user.save!
expect(@user.confirmed_at).to be_nil
end

it "should call the send_confirmation_instructions method" do
@user.should_receive(:send_confirmation_instructions) {}
@user.save!
end
end

def user_atts
# return attributes hash
end
end

这是一个非常简单的示例,但在我的规范中有很多类似的实例,并且在大多数情况下,它们都将记录持久保存到数据库中。我很乐意利用 RSpec 的 letsubject 帮助器,但我不确定它们在这里是否有用。

我一直在使用FactoryGirl很多,并认为它的 build_stubbed 策略可能会稍微加快我的规范,但我找不到很多有助于限制实际记录创建的实例(或者我不知道如何使用)。

我假设在某些情况下测试需要 记录创建,但上面的例子看起来不像其中之一。我什至应该尝试重构它还是编写这些测试更好?任何帮助将不胜感激。

最佳答案

我的测试可能看起来像这样。

describe User do
let(:user) { FactoryGirl.build_stubbed(:user) }

context "record creation" do
it "should generate a confirmation_token" do
user.save!
expect(user.confirmation_token).to be_present
end

it "should set the confirmed_at attribute to nil" do
user.save!
expect(user.confirmed_at).to be_nil
end

it "should call the send_confirmation_instructions method" do
expect(user).to receive(:send_confirmation_instructions).once
user.save!
end
end
end

那是使用 Factory Girl 创建用户模型。另外,按照@RahulGarg 的说法,我会让 DatabaseCleaner 在每次测试后清除数据库

你所要做的就是在你的 spec_helper 中配置这样的东西

  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

这意味着每次测试后数据库都会被清除。

关于ruby-on-rails - 编写 Rails 测试,不要保留那么多数据库对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444504/

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