Martin Foot
Martin Foot

Reputation: 3664

How can I access models from the parent application inside rspec tests for a rails engine?

I have a rails application which has a mountable engine inside it. I'm currently setting up rspec tests for the mountable engine. These require access to the models and helpers from the parent application. I'm aware that there is some coupling here but this is not a re-usable component and the engine is being used for providing additional functionality that is otherwise separate from the parent application.

I'm able to run these tests in the dummy application that is created from the rails new plugin command but this does not have access to the parent application models.

How can I configure my spec helper such that it will load models and configuration settings from the parent application? Ideally this would include any configuration in the parent application's spec_helper.rb.

I believe I should be able to use my parent application instead of the dummy application but have been unsuccessful so far. I am forced to include all gems from the parent application into my engine's Gemfile and have NameErrors for other mounted engines inside the parent application when trying to run my specs.

Upvotes: 5

Views: 687

Answers (1)

Mori
Mori

Reputation: 27779

We load the parent spec_helper like this, from within the child's spec_helper:

path = Gem.loaded_specs.select {|k,_| k == 'parent-gem-name'}
  .first.last.full_gem_path
file = File.join(path, 'spec', 'spec_helper.rb')
instance_eval File.read(file), __FILE__, __LINE_

Upvotes: 1

Related Questions