我在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
我想测试我的模型,并想用作第一次测试孩子的验证:
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
我的儿童装置看起来像这样:
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
我无法看到,我做错了什么...
我想,这是一个非常简单的错误......
谢谢你的帮助!
答案 0 :(得分:3)
我的验证测试产生以下错误是假的,我不明白,我做错了什么
这意味着@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"
这看起来不像是有效的用户对象。