11

If I run test case:

ruby test/models/chat_bot/option_test.rb

I get error:

/home/anuja/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- test_helper (LoadError)

and it works if I run test as follow:

rake test test/models/chat_bot/option_test.rb
Anuja
  • 646
  • 4
  • 14

6 Answers6

9

You need to add your test directory to Ruby's load path. Otherwise Ruby doesn't know where to look to find test_helper. To add to the load path, use the -I option:

ruby -Itest test/models/chat_bot/option_test.rb
Matt Brictson
  • 10,904
  • 1
  • 38
  • 43
  • 1
    I fixed this by adding absolute path: require ''./test/test_helper'' instead of require 'test_helper'. – Anuja Sep 21 '16 at 09:41
8

It is fixed by adding absolute path:

require './test/test_helper'

instead of:

require 'test_helper'

wherever we require the same. And then I can run test case without any parameter:

ruby test/models/xyz/option_test.rb
Anuja
  • 646
  • 4
  • 14
  • Now 2019. The popular "how tos" don't work - hours with error after error w/o ever getting to the job at hand. Until the buggy-test frameworks are fixed (with automated setup), the best workaround is to manually-include each file by absolute-path. – JosephK Aug 16 '19 at 04:07
2

Somehow running rails test <test_file_path> from my project's root solves the issue.

Marat
  • 622
  • 7
  • 21
0

Run the test as the rails guide says:

bin/rails test test/controllers/CONTROLLERNAME_controller_test.rb
caglar
  • 279
  • 2
  • 5
0

Ruby must know where test_helper exist.

Either like Matt said on CLI with ruby like

ruby -Itest test/models/chat_bot/option_test.rb

or if run from a rake task, the same must be done in the Rakefile

Rake::TestTask.new do |t|
  t.libs << "test"          # <--- this!
  t.test_files = FileList["test/**/*_test.rb"]
end
desc "Run tests"

as documented here.

Then it should work fine to include test_helper in test/models/chat_bot/option_test.rb like

require 'test_helper'
...
Erikw
  • 799
  • 6
  • 18
0

You could also add

$LOAD_PATH.unshift File.expand_path("../test", __dir__)

before

require "test_helper"

It adds the test folder to the global variable LOAD_PATH. Which is used for searching Ruby scripts and extension libraries used by Kernel#load and Kernel#require.