Using Ruby and Minitest, how do I run the same testcase with different data, controlled only by a list Using Ruby and Minitest, how do I run the same testcase with different data, controlled only by a list ruby ruby

Using Ruby and Minitest, how do I run the same testcase with different data, controlled only by a list


You could dynamically define the methods.

In the following example, 6 tests are dynamically created (2 tests for each of the 3 values being tested). This means that if anything fails, the other tests still run.

require "minitest/autorun"class MyTests < MiniTest::Unit::TestCase    ['0', '1111111', '2222222'].each do |phone_number|        define_method("test_#{phone_number}_has_7_characters") do            assert_equal(7, phone_number.length)        end        define_method("test_#{phone_number}_starts_with_1") do            assert_equal('1', phone_number[0])        end    endend

The apply test case gives the following results:

# Running tests:F..F.FFinished tests in 0.044004s, 136.3512 tests/s, 136.3512 assertions/s.  1) Failure:test_0_starts_with_1(MyTests) [stuff.rb:13]:Expected: "1"  Actual: "0"  2) Failure:test_0_has_7_characters(MyTests) [stuff.rb:9]:Expected: 7  Actual: 1  3) Failure:test_2222222_starts_with_1(MyTests) [stuff.rb:13]:Expected: "1"  Actual: "2"6 tests, 6 assertions, 3 failures, 0 errors, 0 skips

Applying the same concept to your tests, I think you want:

class MyTests < MiniTest::Unit::TestCase    listOfPhoneNumbersForTesting.each do |phone|        define_method("test_#{phone}") do            TestPhone.new phone        end    endend

A similar approach can be taken when using the spec-style tests:

require 'minitest/spec'require 'minitest/autorun'describe "my tests" do  ['0', '1111111', '2222222'].each do |phone_number|    it "#{phone_number} has 7 characters" do      assert_equal(7, phone_number.length)    end    it "#{phone_number} starts with 1" do      assert_equal('1', phone_number[0])    end  endend

IMPORTANT: One thing to note is that you need to make sure that the name of the test methods created are unique for each test case.

For example, if you do not put the phone number in the method name, you end up overwriting your previously defined methods. Ultimately this means that only the last phone number gets tested.

This is because MiniTest generates the test methods on the fly and will overwrite already generated test methods, ultimately only using the last .each variable.