Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby unit tests, how to assert that a string contains certain substring?

In a Ruby unit test, how do I assert that a string contains a substring? Something like:

assert_contains string_to_test, substring_to_verify 
like image 797
Louis Rhys Avatar asked Apr 20 '13 14:04

Louis Rhys


People also ask

How do you assert in Ruby?

the assert_equal() Method in Ruby If we want to test if the expected result is the same as the actual result, we can use another method, assert_equal() , that takes in the expected result, actual result, and the failure message.

How do you write unit tests in Ruby?

Unit testing is a great way to catch errors early in the development process, if you dedicate time to writing appropriate and useful tests. As in other languages, Ruby provides a framework in its standard library for setting up, organizing, and running tests called Test::Unit.


1 Answers

You could go with assert_match pattern, string, [message] which is true if string =~ pattern:

assert_match substring_to_verify, string_to_test 

e.g.

assert_match /foo/, "foobar" 

If you use this very often, why not write your own assertion?

require 'test/unit'  module Test::Unit::Assertions   def assert_contains(expected_substring, string, *args)     assert_match expected_substring, string, *args   end end 

Alternatively, using the method described by @IvayloStrandjev (way easier to understand), you could define

require 'test/unit'  module Test::Unit::Assertions   def assert_contains(expected_substring, string, *args)     assert string.include?(expected_substring), *args   end end 

The usage is exactly as you requested in your question, e.g.

class TestSimpleNumber < Test::Unit::TestCase   def test_something     assert_contains 'foo', 'foobar'   end    def test_something_fails     assert_contains 'x', 'foobar', 'Does not contain x'   end end 

Which will produce

Run options:  # Running tests:  .F  Finished tests in 0.000815s, 2453.9877 tests/s, 2453.9877 assertions/s.    1) Failure: test_something_fails(TestSimpleNumber) [assertion.rb:15]: Does not contain x  2 tests, 2 assertions, 1 failures, 0 errors, 0 skips 

Edit

As requested, with automated message:

module Test::Unit::Assertions   def assert_contains(exp_substr, obj, msg=nil)     msg = message(msg) { "Expected #{mu_pp obj} to contain #{mu_pp exp_substr}" }     assert_respond_to obj, :include?     assert obj.include?(exp_substr), msg   end end 

adapted from the original assert_match source. This actually also works with Arrays!

assert_contains 3, [1,2,3] 
like image 87
Patrick Oscity Avatar answered Sep 18 '22 05:09

Patrick Oscity