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

标签 ruby-on-rails ruby unit-testing validation testing

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

单元测试代码

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/

相关文章:

ruby-on-rails - Rails 模型生成器工具

ruby-on-rails - 如何在 Rackspace 云存储上使用carrierwave控制缓存?

ruby-on-rails - Rails 插件的功能测试,assert_template 损坏了吗?

css - Bootstrap-table css 在 ajax 调用后不加载

ruby-on-rails - quill js羊皮纸错误

ruby-on-rails - 确保 'gem install ~ ' 绑定(bind)成功

ruby-on-rails - Ruby:如何在 fixture 中配置枚举?

unit-testing - .Net Core 项目 : Tests not discovered 的 VSTS 单元测试

ruby-on-rails - ruby 从数组中添加字符串

ruby-on-rails - 添加字段以使用 Rails 4 设计注册