4

I recently created my first Rails engine. The only thing in /config is routes.rb - no environment.rb or application.rb or anything like that.

When I installed the rspec-rails gem and tried to run my specs, I got an error saying it couldn't find environment.rb, which is not surprising, since environment.rb doesn't exist.

The confusing thing to me is that the evidence I have tells me one of two things must be the case:

1) Rails engines don't come with an environment.rb and you're expected to create environment.rb, application.rb, etc. by hand. This seems unlikely.

2) Rails engines do come with an environment.rb, but my engine happens to be missing it for whatever reason. This also seems unlikely. I am confused, though, by this answer that refers to environment.rb in an engine: Testing Rails 3.1 mountable engine with Rspec

So my question is: Are Rails engines supposed to come with an environment.rb, and if not, how are you supposed to create one if you want/need one?

Community
  • 1
  • 1
Jason Swett
  • 43,526
  • 67
  • 220
  • 351

2 Answers2

4

Use the dummy app's environment.rb file.

To setup RSpec:

Add the below to your spec_helper.rb file.

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../test/dummy/config/environment", __FILE__)
...

It's also helpful to add the engine root.

ENGINE_RAILS_ROOT = File.join(File.dirname(__FILE__), '../')

If you want access to the engine's routing helpers, add the below in the RSpec.configure block.

# This will include the routing helpers in the specs so that we can use
# <engine>_path, etc., to get to the routes.
config.include <RailsEngine>::Engine.routes.url_helpers

Hope that helps.

Jason Swett
  • 43,526
  • 67
  • 220
  • 351
Ken
  • 7,847
  • 1
  • 21
  • 20
  • That did it, thanks. I didn't understand before that "dummy" was an actual thing, not just a placeholder like "foo" or "your-app-name-here". Also, I made a couple small editions to your answer because I had to tweak your paths to get my specs to actually run. – Jason Swett Feb 22 '13 at 18:40
0

Rails engines may have environment files, but they don't need them. I would recommend against them, because your application is probably going to get mounted (as a gem) inside of another application, making it very difficult to configure your engine from within the main rails application.

It's more advisable that you use a yml file that can be configured from within the primary rails app, and allow that rails app to implement environment specific configurations. That doesn't mean you can't have some defaults that are based on environment environment files inside of your rails engine, but rather, that it usually makes life easier to allow external configuration.

Christopher WJ Rueber
  • 2,141
  • 15
  • 22