Module: ActiveSupport::Testing::Parametrized

Included in:
ActiveSupport::TestCase
Defined in:
lib/active_support/testing/parametrized.rb

Instance Method Summary collapse

Instance Method Details

#param_test(description_template, parameters, &block) ⇒ Object

Generates parametrized tests, one for each set of parameters given. The description must be a format specification with the same number of substitutions as each parameter set has arguments (generally, just use one ā€˜%sā€™ substitution per parameter). The body of the test is the given block executed with each parameter set.

Examples

This code within an ActiveSupport::Testcase

param_test "string %s is ASCII only",
["foo", "bar", "baz"] do |string|
  assert string.ascii_only?
end

Generates 3 test methods, one for each parameter given, with names based on the description.

Another example with multiple parameters, generating 2 test methods:

param_test "%s is uppercase %s",
[["FOO", "foo"], ["BAR", "bar"]] do |expected, param|
  assert_equal expected, param.upcase
end


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/active_support/testing/parametrized.rb', line 30

def param_test(description_template, parameters, &block)
  param_count = format_sequence_count(description_template)

  if param_count != block.arity
    raise ArgumentError, "Number of arguments expected in description template " +
      "'#{description_template}', doesn't match number of argument to block (#{block.arity})"
  end

  parameters.each do |param_set|
    # Replacing nil values with 'nil' string because nil values will
    # get converted to an empty string within a test name.
    if param_set.kind_of? Array
      sanitized_param_set = param_set.map do |param|
        param.nil? ? 'nil' : param
      end
    else
      sanitized_param_set = param_set.nil? ? ['nil'] : [param_set]
    end

    if param_count != sanitized_param_set.size
      raise ArgumentError, "Parameter set #{sanitized_param_set} doesn't match number " +
        "of arguments expected by description template '#{description_template}'"
    end

    # Make sure the description generates a unique test method name.
    description = description_template % sanitized_param_set
    unique_description = description
    if instance_methods.include? generate_test_name(unique_description)
      count = 1
      description += " %s"
      unique_description = description % count
    end
    while instance_methods.include? generate_test_name(unique_description)
      count += 1
      unique_description = description % count
    end

    test unique_description do
      instance_exec param_set, &block
    end
  end
end