Rails:重复单元测试 - 干?

时间:2012-10-29 15:14:10

标签: ruby-on-rails ruby-on-rails-3 unit-testing tdd dry

是否有任何标准做法来清除轨道中的重复单元测试用例。对于例如我有很多带有“name”属性的模型,我想为每个模型做同样的单元测试。我隐约看到我需要创建模块才能重用?这可能/正确吗?

创建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

1 个答案:

答案 0 :(得分:1)

将重复代码移动到模块中并将其包含在实际测试中(如在类中)。