Search code examples
ruby-on-railsrubyruby-on-rails-4rspecrspec-rails

RSpec doesn't load my class even though it loads in the Rails console


I've got a class inside app/models/parser called data.rb with contents :

class Parser::Data 
  def method1
  end
end

Nothing fancy at this point. I'm trying to write a test for it before implementing too much, just did default RSpec install for Rails.

My RSpec file is in spec/models/parser/data_spec.rb and is very basic so far:

require 'spec_helper.rb'

describe Parser::Data do
  let(:parser) { Parser::Data.new }
end

When I run the test I get this error:

spec/models/parser/data_spec.rb:3:in `<top (required)>': uninitialized constant Parser (NameError)

I tried placing module Parser around the Data class in the same directory app/models/parser, also I've tried moving it to lib/parser doing the same module wrapping class, and added lib/parser to autoload in the application.rb but nothing has worked so far.

What am I doing wrong?


Solution

  • require 'rails_helper' instead of spec_helper. Requiring only spec_helper reproduces the issue for me, and requiring rails_helper fixes it. More on spec_helper vs. rails_helper (including performance implications) here: How is spec/rails_helper.rb different from spec/spec_helper.rb? Do I need it?

    I reproduced the problem by running RSpec with bundle exec rspec. If I run RSpec with bin/rspec (that's a binstub generated by the spring-commands-rspec gem) it doesn't care which helper file I require. I guess spring loads more eagerly.