gpt4 book ai didi

ruby-on-rails - 如何使用 'assert_difference' 为两个不同的对象断言两个不同的值?

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

我有以下测试:

it 'create action: a user replies to a post for the first time' do
login_as user

# ActionMailer goes up by two because a user who created a topic has an accompanying post.
# One email for post creation, another for post replies.
assert_difference(['Post.count', 'ActionMailer::Base.deliveries.size'], 2) do
post :create, topic_id: topic.id, post: { body: 'Creating a post for the first time.' }
end
email = ActionMailer::Base.deliveries

email.first.to.must_equal [user.email]
email.subject.must_equal 'Post successfully created'
must_redirect_to topic_path(topic.id)

email.last.to.must_equal [user.email]
email.subject.must_equal 'Post reply sent'
must_redirect_to topic_path(topic.id)
end

上面的测试由于代码中的 assert_difference block 而中断。为了让这个测试通过,我需要让 Post.count 递增 1,然后让 ActionMailer::Base.deliveries.size 递增 2。该场景将使测试通过。我已尝试将代码重写为第二种类型的测试。

it 'create action: a user replies to a post for the first time' do
login_as user

assert_difference('Post.count', 1) do
post :create, topic_id: topic.id, post: { body: 'Creating a post for the first time.' }
end

# ActionMailer goes up by two because a user who created a topic has an accompanying post.
# One email for post creation, another for post reply.
assert_difference('ActionMailer::Base.deliveries.size', 2) do
post :create, topic_id: topic.id, post: { body: 'Creating a post for the first time.' }
end

email = ActionMailer::Base.deliveries

email.first.to.must_equal [user.email]
email.subject.must_equal 'Post successfully created'
must_redirect_to topic_path(topic.id)

email.last.to.must_equal [user.email]
email.subject.must_equal 'Post reply sent'
must_redirect_to topic_path(topic.id)
end

第二次迭代接近我想要的但又不完全是。此代码的问题在于,由于 assert_difference block 中的创建调用,它将创建两次 post 对象。我查看了 rails api 指南中的 assert_difference 代码和在此处找到的 api docks(assert_difference API dock 但这不是我需要的。我需要这样的东西:

assert_difference ['Post.count','ActionMailer::Base.deliveries.size'], 1,2 do
#create a post
end

有没有办法实现它?

最佳答案

你可以像这样嵌套它们:

assert_difference("Post.count", 1) do
assert_difference("ActionMailer::Base.deliveries.size", 2) do
# Create a post
end
end

关于ruby-on-rails - 如何使用 'assert_difference' 为两个不同的对象断言两个不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29101419/

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