DEV Community

Akshay Khot
Akshay Khot

Posted on

Running a Single Test with Spaces in Minitest

In Rails, if you want to run a specific test without the others in the file, you can pass the method's name to the --name flag.

def test_controller_name
  # assert ...
end

>  ruby -I test test/controller/renderer_test.rb --name test_controller_name
Enter fullscreen mode Exit fullscreen mode

But, Rails also provides a test method that takes a test name and a block.

test "creating from a controller" do
  # assert ...
end
Enter fullscreen mode Exit fullscreen mode

How do you run this test that allows you to pass a string containing spaces?

For this, we need to step inside the test method and see what it's doing. If we open the source code for the test method, this is what it does:

def test(name, &block)
  test_name = "test_#{name.gsub(/\s+/, '_')}".to_sym
  defined = method_defined? test_name
  raise "#{test_name} is already defined in #{self}" if defined
  if block_given?
    define_method(test_name, &block)
  else
    define_method(test_name) do
      flunk "No implementation provided for #{name}"
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

The first line replaces all the spaces in the name string with an underscore _, and adds a test at the beginning. So, the test name creating from a controller becomes test_creating_from_a_controller. Then, using metaprogramming, it defines a method with that same name. So the above test method becomes:

def test_creating_from_a_controller
  # assert ...
end
Enter fullscreen mode Exit fullscreen mode

Now that you know the name, you can run this test as follows:

>  ruby -I test test/controller/renderer_test.rb -n test_creating_from_a_controller
Enter fullscreen mode Exit fullscreen mode

Hope this helps.

Top comments (0)