我正在为我的一个 Rails 模型编写一些单元测试。这是一个大型模型,在某些情况下,我对许多方法有几十个断言。我更喜欢将普通的 test/unit 与 rails 的 activesupport 语法一起使用,所以我有一个这样的文件:
require 'test_helper'
class ItemTest < ActiveSupport::TestCase
test "for_sale? should be true if cond 1..."
test "for_sale? should be true if cond 2..."
test "for_sale? should be true if cond 3..."
test "for_sale? should be true if cond 4..."
test "for_sale? should be false if cond 1..."
test "for_sale? should be false if cond 2..."
test "for_sale? should be false if cond 3..."
test "for_sale? should be false if cond 4..."
end
等等每个方法。问题是测试变得越来越复杂,因为我不能再依赖 setup() 因为每组测试的上下文对于每种方法来说都大不相同。此外,很难在不运行所有测试的情况下仅测试我正在使用的方法。
其他人如何管理这样的大型测试用例?有最佳实践吗?
最佳答案
如果您想坚持使用测试/单元,我建议您使用 shoulda。您不需要使用 shoulda 宏,但它会给您一个适用于此的非常漂亮的功能:上下文。它允许您将单元测试分解为单独的部分,并且可以嵌套这些部分。
context "as a really cool user" do
test "test number one..."
end
context "as a lame user" do
test "test number two..."
end
从那里您可以继续使用所有测试/单元语法,或者如果应该赢得您的支持 - 您可以切换或混合匹配。
关于ruby - 我应该如何在 ruby 中拆分大型单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3096691/