gpt4 book ai didi

ruby-on-rails - 如何重新加载由 let 定义的变量

转载 作者:数据小太阳 更新时间:2023-10-29 07:40:14 25 4
gpt4 key购买 nike

一个 user 有很多 comments,所以我想有一个工厂 user 有一个 comment 关联对它(user_with_comment):

factory :user, class: User  do |t|
...
factory :user_with_comment do |t|
after(:create) do |user|
FactoryGirl.create(:comment, user_id: user.id)
end
end

它工作正常...当我调用 FactoryGirl.create(:user_with_comment) 时,它会创建 user 和相关的 comment我的测试数据库

但是,我在 controller_spec 中遇到了一些问题:

使用 let 我必须重新加载 user 才能看到 comment:

let(:user) { FactoryGirl.create(:user_with_comment) }
user.comments.size #=>0
user.reload
user.comments.size #=>1

一个解决方案是使用 before(:each),但它会在每次测试之前创建 vendacomment:

before(:each) do
@user = FactoryGirl.create(:user_with_comment)
end
@user.comments.size #=>1

或者,我可以在每次测试前重新加载用户,但它也会访问数据库:

let(:user) { FactoryGirl.create(:user_with_comment) }
before(:each) do
user.reload
end

在这种情况下最好的方法是什么?

最佳答案

这与 let 是延迟求值的事实有关,并且在创建用户后添加了用户工厂的注释。

Note that let is lazy-evaluated: it is not evaluated until the first time the method it defines is invoked.

参见 RSpec documentation让和让!

使用 let 意味着当您第一次在示例中使用它时创建了用户,因此之后创建了评论。你可以使用让!在每个示例之前创建用户以避免重新加载。如果您在规范中的所有/大多数示例中使用工厂,这不会对您的测试产生负面影响。

关于ruby-on-rails - 如何重新加载由 let 定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28482755/

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