我正在尝试整个 TDD,但在验证存在方面遇到了问题。我有一个名为 Event
的模型,我想确保在创建 Event
时,title
是 price
并且存在摘要
。
单元测试代码
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/