Search code examples
ruby-on-railsrspecmodels

How can I get Rspec2 to support models and specs in a different path?


I have two rails projects which share the same models (a public website and a an admin site) via a git submodule.

In my application.rb file I have added the following line: config.autoload_paths += ["shared/models", "shared/lib"], and this works fine while running the Rails applications, however when I try to run specs it seems to load the routes.rb file first, and then the application.rb file - which means that the specs error out - especially with devise.

In addition to this, Rspec wont pickup the specs in the shared/spec path - is there any way to add this path to the spec task, like do I need to setup my own rspec.rake file duplicating the task or something like that?

Cheers


Solution

  • To load shared/models, you do have to add it to config.autoload_paths.

    Then to load your spec from shared/spec, add this to spec_helper.rb:

    
    shared_model_specs = config.filename_pattern.split(",").collect do |pattern|
      Dir["shared/spec/models/#{pattern.strip}"]
    end.flatten
    config.files_to_run.concat shared_model_specs 
    

    Just a side note for other guys interested, if your spec files are in the normal spec folder but under a customized sub folder, you can load it like this:

    
    config.include RSpec::Rails::ModelExampleGroup, :type => :model, :example_group => {
      :file_path => config.escaped_path(%w[spec shared models])
    }  
    

    PS: I would recommend putting the shared code or modules into a gem, then use them in the two projects. This way the gem contains its own tests and referencing it from multiple projects is much easier and organized.