I have a test that tries to test a class located in lib folder.
Right now I do this in my parser_spec.rb
require 'spec_helper'
require 'parser' --> Because my class is /lib/parser.rb
describe "parser" do
it "needs a url to initialize" do
expect { Parser.new }.to raise_error(ArgumentError)
end
end
What would be the correct way to include all the lib files, so that they are in the scope of the rspec tests?
Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.
Open your terminal, cd into the project directory, and run rspec spec . The spec is the folder in which rspec will find the tests. You should see output saying something about “uninitialized constant Object::Book”; this just means there's no Book class.
Open coverage/index. html in your browser window to view the report. Try to get the coverage to 100% by writing RSpec tests. Every time you add a test, run rspec to see if the test is passing.
I use the database_cleaner gem to scrub my test database before each test runs, ensuring a clean slate and stable baseline every time. By default, RSpec will actually do this for you, running every test with a database transaction and then rolling back that transaction after it finishes.
The way you've done it -- require 'parser'
is the recommended way. RSpec puts lib
on the $LOAD_PATH
so that you can require files relative to it, just like you've done.
Try this
require_relative "../../lib/parser.rb"
or
require 'lib/parser.rb'
rspec automatically loads 'spec/spec_helper.rb' when it runs, and it also automatically adds the 'lib' folder to it's LOAD_PATH, so that your requires in 'lib/parser.rb' are seen and required properly.
Just put the 'lib' folder to autoload_path. For example, in application.rb
config.autoload_paths += "#{Rails.root}/lib/"
Then you can do it normally
require 'spec_helper'
describe Parser do
...
end
In order to avoid lib
autoload as Ryan Bigg said, you can autoload a custom directory placed in the app root:
Into /your/config/application.rb you can add:
config.autoload_paths += %W(#{config.root}/my_stuff)
Then, you can do:
require 'spec_helper'
describe Parser do
#your code...
end
Maybe, you can put your class inside a module in order to avoid collisions:
class MyStuff::Parser
#your code...
end
Then, you can do:
require 'spec_helper'
describe MyStuff::Parser do
#your code...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With