gpt4 book ai didi

ruby-on-rails - Rails 测试模型说 'Expected false to be truthy'

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

我有一个网站,用户可以在其中创建产品,并且产品可以有 list 。

我有一个包含以下列的 list 表:-

id  |  product_id  | content  |  archived 

我是 Rails 测试的新手。我在下面写了测试

  test 'should have content' do
checklist = Checklist.new
assert checklist.save
end

然后用下面的命令运行测试

ruby -I test test/models/checklist_test.rb

测试失败,出现Expected false to be truthy 错误。

是否因为可以使用 user.product.checklists 访问 list 的问题,我必须先在固定装置中填充数据并在测试中调用它们?

编辑 1

我在 list 模型中没有任何验证。

class Checklist < ApplicationRecord
belongs_to :product
end

我在测试中添加了 ! 保存,如下所示

  test 'should have content' do
checklist = Checklist.new
assert checklist.save!
end

得到这个错误

ActiveRecord::RecordInvalid: Validation failed: Product must exist

因为表中有 product_id。我不知道如何向 Rails 测试提供数据。有帮助吗?

编辑 2

如下修改后错误消除。

class Checklist < ApplicationRecord
belongs_to :product, optional: true
end

但是我想用 product 测试模型展示。我不知道如何使用固定装置向测试提供数据,就好像没有我可以使用的外键一样 Checklist.new在测试中。

因为它有外键,我如何向 Checklist 提供数据?因为它属于 Product它本身属于 User

最佳答案

checklist.save 如果 checklist 由于某种原因未能保存,将返回 false;大概是因为验证失败

例如,您的 app/models/checklists.rb 可能包含如下内容:

validates :product_id, presence: true

或者:

validates :content, length: { minimum: 10 }

等等。在这个简单的场景中,您可能只需查看模型定义就可以轻松确定错误;但对于更复杂的应用程序,您可以查看:checklist.errors.messages 以查看记录未能保存的原因列表。

从测试名称(“应该有内容”)来看,我的猜测是它失败了,因为content 不能为空!

例如,为了让这个测试通过,你可能需要这样写:

test 'should have content' do
checklist = Checklist.new(content: 'hello world')
assert checklist.save
end

人们在测试这类事情时使用的一种常见方法是在 factories 中定义一个“有效记录” ;这使您可以显式测试无效 记录,而不必在很多地方显式地重新定义有效记录。例如,在这里你可以这样做:

# test/factories/checklists.rb
FactoryBot.define do
factory :checklist do
content 'test content'
end
end

# test/models/checklist_test.rb
test 'should have content' do
checklist = build(:checklist, content: nil)
refute checklist.save # Expecting this to FAIL!
assert_includes "Content cannot be nil", checklist.errors
end

(代码可能不是 100% 完整/准确;但您明白了)

关于ruby-on-rails - Rails 测试模型说 'Expected false to be truthy',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49862493/

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