Like most people, I have learned Rails before Ruby and now I would like to get a better knowledge of Ruby.
I am making some scripts and I would like to test them.
I was surprised by the fact that you can’t use Rails’ test syntax in plain ruby scripts. The following code does not work:
require "test/unit"
class MyTest < Test::Unit::TestCase
test "one plus one should be equal to two" do
assert_equal 1 + 1, 2
end
end
# Error: wrong number of arguments (1 for 2) (ArgumentError)
You have to use this code instead:
require "test/unit"
class MyTest < Test::Unit::TestCase
def one_plus_one_should_be_equal_to_two
assert_equal 1 + 1, 2
end
end
Which seems less readable to me.
Is it possible to use the "declarative" syntax in plain Ruby scripts?
According to Rails’ APIs, the
testmethod is defined inside ActiveSupport::Testing::Declarative module and uses a sort of metaprogramming to add new test methods.If you don’t already have the Rails gem installed, you can just install the activesupport gem:
Now you just have to require it and make your class inherit from
ActiveSupport::TestCase.Here is the complete code: