2

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?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Gandalf StormCrow
  • 25,788
  • 70
  • 174
  • 263

1 Answers1

2

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.

Community
  • 1
  • 1
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
  • Requiring `rails_helper` causes the entire rails environment to load (which in turn enables rails constant auto-loading, fixing the issue). If your class does not depend on rails, I recommend _not_ requiring `rails_helper` -- if you require it, the boot time to run your spec file goes way up. Instead, I recommend you just add a simple `require` to the top of the spec file to load the `parser/data.rb` file. – Myron Marston Apr 19 '16 at 16:51
  • @MyronMarston I'd vote for that if you wrote it as an answer. Not an issue if one is using spring, though. Updating ... – Dave Schweisguth Apr 19 '16 at 17:19