是否有任何标准做法来干燥 Rails 中的重复单元测试用例。例如,我有许多具有“名称”属性的模型,我想对每个模型进行相同类型的单元测试。我隐约看到我需要创建的模块是重用的?那可能/正确吗?
创建 DRY 单元测试的任何指针/实践?
示例代码:我想对具有相同命名属性的许多其他模型进行相同类型的测试。
require 'test_helper'
# Factory class
class UserFactory
# Creates a valid template user
def self.create
user = User.new do |u|
u.name = "Test User #{rand}"
u.notes = "test notes"
end
user
end
end
class UserTest < ActiveSupport::TestCase
# ------------
# Init
# ------------
def setup
@valid_usr = UserFactory.create
end
def teardown
@valid_usr.destroy if @valid_usr.persisted?
@valid_usr = nil
end
# ------------
# Name
# ------------
test "should not have a dummy user object" do
user = User.new
assert !user.save
end
test "unique user name must be saved" do
assert UserFactory.create.save!, "First entry must be saved"
user = UserFactory.create
user.name = "Different name"
assert user.save!, "Unique user must be saved"
user.destroy
end
test "non unique user names must not be saved" do
user1 = UserFactory.create
user2 = UserFactory.create
user1.name = "Same User name"
user2.name = "Same User name"
assert user1.save!, "First entry must be saved"
assert !user2.save, "Duplicate name should not be saved"
user1.destroy
user2.destroy
end
test "should not have user without a valid name" do
# Invalid name
@valid_usr.name = " "
assert !@valid_usr.save
end
end