【问题标题】:Why is this test result backwards?为什么这个测试结果是倒退的?
【发布时间】:2013-05-05 12:20:30
【问题描述】:

我正在使用 Test:Unit 和 Shoulda 编写我的第一个测试,所以这对我来说可能是一个简单的误解,但是给定一个不包含验证的 Pages 模型和一个测试:

#test/unit/page_test.rb    
require 'test_helper'

class PageTest < ActiveSupport::TestCase
  should belong_to(:site)
  should validate_presence_of(:slug)
end

第二次测试按预期失败(假设模型中没有验证):

# Running tests:

[2/2] PageTest#test: Page should require slug to be set.  = 0.02 s
  1) Failure:
test: Page should require slug to be set. (PageTest) [/Users/Matt/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/shoulda-context-1.1.1/lib/shoulda/context/context.rb:339]:
Did not expect errors to include "can't be blank" when slug is set to nil, got error: 

Finished tests in 0.115436s, 17.3256 tests/s, 17.3256 assertions/s.
2 tests, 2 assertions, 1 failures, 0 errors, 0 skips

但是错误消息Did not expect errors to include "can't be blank" when slug is set to nil 似乎倒退了。不应该这样读:Expected errors to include "can't be blank",因为如果我正在测试的验证存在,那么当 slug 为 nil 时,您会期望验证中出现错误,即 slug“不能为空”。

如果我添加验证,则测试通过,但我希望先看到它正确失败!

另外,为什么第一个测试通过了?我的页面模型不包含 belongs_to 关联!

测试很糟糕! :-(

【问题讨论】:

  • “应该”调用哪个对象?你的测试不应该有上下文和描述吗? “it”子句在哪里?这是 RSpec,不是吗?
  • 不,Test::Unit with shoulda - 认为最好先学习“Rails 方式”,然后再开始使用 RSpec。

标签: ruby-on-rails unit-testing shoulda


【解决方案1】:

这是shoulda 旧版本中的一个错误。您可以查看this thread 了解更多信息。

当我更新到最新版本(现在是 2.2.0)时,我看到了正确的行为和消息,例如 Expected errors to include...

【讨论】:

  • 感谢您的确认。很遗憾,我的第一次测试在 shoulda 中发现了这个错误,因为它让我放弃了这个组合,我转而使用 RSpec(作为一个测试新手而不致力于一个套件的奢侈)。尽管在链接的线程中读到应该在某些地方的测试覆盖率很差,但我很高兴(也有点惊讶)! ;-)
  • RSpec 是一个测试套件,如果您愿意的话,“应该”是它的众多“语言”之一。我听说你可能被推迟了,但我已经使用它们足够长的时间了,仍然衷心推荐它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 2023-02-11
  • 1970-01-01
相关资源
最近更新 更多