mbigras mbigras - 13 days ago 6
Ruby Question

Hello world minitest cli example

Given the following directory structure:

➜ ~/D/w/t/foo tree .
.
├── app.rb
├── foo.rb
└── test
└── test_foo.rb

1 directory, 3 files


If I run
app.rb
I get the classic "Hello world!" response.

➜ ~/D/w/t/foo ruby app.rb
"Hello world!"


Taking a look inside
app.rb
and
foo.rb
:

➜ ~/D/w/t/foo cat app.rb
require_relative 'foo.rb'

Foo.new.bar

➜ ~/D/w/t/foo cat foo.rb
class Foo
def bar
p "Hello world!"
end
end


How would I would I test my
Foo
class with minitest from the commandline?

I know that it has something to do with the
ruby -Ilib
command but I'm not sure what the exact switches and flags are, and also I'm not sure what to put inside of
test_foo.rb
. I'm also not sure if my directory stucture is set up right. Maybe
foo.rb
needs to go inside of a
lib
directory?

Would love you guidance :)

Answer

You can run minitest tests just like ruby files. Just install minitest, write a test, and run like you would a ruby script:

install minitest:

➜  ~/D/w/t/hello-minitest  gem install minitest
Successfully installed minitest-5.9.1
Parsing documentation for minitest-5.9.1
Done installing documentation for minitest after 0 seconds
1 gem installed
➜  ~/D/w/t/hello-minitest  tree .
.
├── app.rb
├── foo.rb
└── test
    └── test_foo.rb

write foo.rb:

class Foo
  def bar
    p "Hello world!"
  end
end

write test:

require 'minitest/autorun'
require_relative '../foo.rb'

class TestFoo < Minitest::Test
  def test_it_works
    assert_equal 1, 1
  end

  def test_bar
    assert_equal Foo.new.bar, "Hello world!"
  end
end

run test like ruby script:

➜  ~/D/w/t/hello-minitest  ruby test/test_foo.rb
Run options: --seed 56777

# Running:

"Hello world!"
..

Finished in 0.001085s, 1843.3179 runs/s, 1843.3179 assertions/s.

2 runs, 2 assertions, 0 failures, 0 errors, 0 skips