gpt4 book ai didi

ruby-on-rails - Ruby 中的模型测试

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

我在使用 ruby​​ 进行模型测试时遇到了一些问题。当我尝试使用验证测​​试时,测试会产生错误。我创建了一个具有以下验证的新模型(子模型)

 class Child < ApplicationRecord

has_many :relations, :dependent => :destroy
accepts_nested_attributes_for :relations
belongs_to :user
validates :user, presence: true
validates :name, presence: true, length: { maximum: 50 }
validates :city, presence: true, :on => :create
validates :postalcode, presence: true, numericality: true
validates :streed, presence: true
validates :add_number, presence: true

validates :disability, presence:true, inclusion: { in: [true, false] }
validates :halal, presence:true, inclusion: { in: [true, false] }
validates :koscha, presence:true, inclusion: { in: [true, false] }
validates :vegetarian, presence:true, inclusion: { in: [true, false] }
validates :vegan, presence:true, inclusion: { in: [true, false] }
validates :allday, presence:true, inclusion: { in: [true, false] }

validates :gender, presence: true

我想测试我的模型并想首先测试 child 的验证:

   def setup
@child = Child.new(name: "Example Child", city: "Example City", postalcode: 13, streed: "Example Street",
add_number: 3, disability: true, gender: 1, halal: true, koscha: false,
vegetarian: false, vegan: false, allday:true, user: "hallo")
end

test "should be valid" do
assert @child.valid?
end

我为 children 准备的装置是这样的:

 one:
name: MyString
city: MyString
postalcode: 1
streed: MyString
add_number: 1
disability: false
halal: false
koscha: false
vegetarian: false
vegan: false
allday: false
gender: 1
user_id: 3

我遇到了问题,我的验证测试产生了以下错误 false to be truth 而我看不到,我做错了什么......我认为,这是一个非常简单的错误......感谢您的帮助!

最佳答案

my validation test produces the following error false to be truth and I can't see, what I've done wrong

这意味着 @child.valid? 返回 false。不是 assert 所期望的。

我也不明白你做错了什么。最有可能的是,某些验证失败。找出哪个是微不足道的。只需检查 @child.errors。例如,像这样。

test "should be valid" do
is_valid = @child.valid? # trigger validation
p @child.errors unless is_valid

assert is_valid
end

我赌这个:

user: "hallo"

这看起来不像是有效的用户对象。

关于ruby-on-rails - Ruby 中的模型测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49322917/

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