gpt4 book ai didi

ruby-on-rails - Rails 验证测试未通过

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

在我们的 Rails 应用程序中,我们有以下模型:

class User < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :calendars, through: :administrations
end

class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end

class Calendar < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :users, through: :administrations
end

我们尝试使用以下 administration_test.rb 测试文件来验证 Administration 模型:

需要'test_helper'

class AdministrationTest < ActiveSupport::TestCase
def setup
@user = users(:noemie)
@administration = Administration.new(user_id: @user.id, calendar_id: @calendar_id)
end

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

test "user id should be present" do
@administration.user_id = nil
assert_not @administration.valid?
end

test "calendar id should be present" do
@administration.calendar_id = nil
assert_not @administration.valid?
end

end

当我们运行测试时,我们得到以下结果:

FAIL["test_calendar_id_should_be_present", AdministrationTest, 2015-06-30 07:24:58 -0700]
test_calendar_id_should_be_present#AdministrationTest (1435674298.26s)
Expected true to be nil or false
test/models/administration_test.rb:21:in `block in <class:AdministrationTest>'

FAIL["test_user_id_should_be_present", AdministrationTest, 2015-06-30 07:24:58 -0700]
test_user_id_should_be_present#AdministrationTest (1435674298.27s)
Expected true to be nil or false
test/models/administration_test.rb:16:in `block in <class:AdministrationTest>'

我们有点迷茫:这是正确的测试方法吗?

如果不是,应该怎么写呢?如果是,我们如何让它通过?

最佳答案

问题不在于您的测试,而在于您期望错误的结果。

belongs_to在 ActiveRecord 中不添加验证,宏只是创建一个关系。

要验证关系,您可以使用 validates_associated它在每个关联记录上调用 #valid? 并调用 validates_presence_of 以确保关联记录存在。

class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
validates_associated :user
validates :user, presence: true
end

当测试验证时,最好将断言写在错误散列上,因为如果验证因任何其他原因失败,assert_not @administration.valid? 将给出误报。

差:

test "user id should be present" do
@administration.user_id = nil
assert_not @administration.valid?
end

好:

test "user id should be present" do
@administration.user_id = nil
@administration.valid?
assert @administration.errors.key?(:user)
end

关于ruby-on-rails - Rails 验证测试未通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31171136/

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