本文介绍了单元测试验证奇怪行为的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I'm trying out the whole TDD and I'm running into a problems with validate presence. I have a model called Event and I want to ensure that when an Event is created that a title a price and a summary exists.

单元测试代码

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 模型中的以下代码.

I run the test I get 3 FAILS. Which is Good.Now I want to to just get the title test to pass first with the following code in the Event model.

class Event < ActiveRecord::Base

  validates :title, :presence => true

end

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

When I re-run the test I get 3 PASSES where I would think I should have gotten 1 PASS and 2 FAILS. Why am I getting 3 PASSES?

推荐答案

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

I have two test helper methods that can make this sort of thing easier to diagnose:

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

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

You'd use them in cases like this:

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

这应该会显示您是否错过了预期的验证,并且还会向您提供有关在预期之外失败的特定验证的反馈.

This should show if you're missing a validation that you expected and will also give you feedback on specific validations that have failed when not expected.

这篇关于单元测试验证奇怪行为的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:42