gpt4 book ai didi

ruby-on-rails - 单元测试验证奇怪行为的存在

转载 作者:数据小太阳 更新时间:2023-10-29 08:52:40 24 4
gpt4 key购买 nike

我正在尝试整个 TDD,但遇到了验证存在的问题。我有一个名为 Event 的模型,我想确保在创建 Eventtitleprice并且存在一个summary

单元测试代码

class EventTest < ActiveSupport::TestCase

test "should not save without a Title" do
event = Event.new
event.title = nil
assert !event.save, "Save the Event without title"
end

test "should not save without a Price" do
event = Event.new
event.price = nil
assert !event.save, "Saved the Event without a Price"
end

test "should not save without a Summary" do
event = Event.new
event.summary = nil
assert !event.save, "Saved the Event without a Summary"
end

end

我运行了测试,我得到了 3 次失败。哪个好。现在我只想让 title 测试先通过 Event 模型中的以下代码。

class Event < ActiveRecord::Base

validates :title, :presence => true

end

当我重新运行测试时,我得到了 3 次通过,而我认为我应该得到 1 次通过和 2 次失败。为什么我获得了 3 个通行证?

最佳答案

我有两个测试辅助方法可以使这类事情更容易诊断:

def assert_created(model)
assert model, "Model was not defined"
assert_equal [ ], model.errors.full_messages
assert model.valid?, "Model failed to validate"
assert !model.new_record?, "Model is still a new record"
end

def assert_errors_on(model, *attrs)
found_attrs = [ ]

model.errors.each do |attr, error|
found_attrs << attr
end

assert_equal attrs.flatten.collect(&:to_s).sort, found_attrs.uniq.collect(&:to_s).sort
end

你会在这样的情况下使用它们:

test "should save with a Title, Price or Summary" do
event = Event.create(
:title => 'Sample Title',
:price => 100,
:summary => 'Sample summary...'
)

assert_created event
end

test "should not save without a Title, Price or Summary" do
event = Event.create

assert_errors_on event, :title, :price, :summary
end

这应该会显示您是否缺少预期的验证,并且还会为您提供有关在意外情况下失败的特定验证的反馈。

关于ruby-on-rails - 单元测试验证奇怪行为的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993068/

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