Testing Rails 3.1 mountable engine with Rspec

deb picture deb · Sep 17, 2011 · Viewed 12.5k times · Source

I started making a Rails 3.1 engine, and I'm having a hard time testing it using rspec.

First of all, if I run rails g integration_test whatever it creates a regular integration test in tests/integration instead of spec/requests (the rspec-rails gem is installed and required as a development dependency in the gemspec file)

Also, when I run a spec test I get an error saying the table corresponding to the model I'm testing has not been created. I tried rake engine_name:install:migrations and running rake db:migrate from inside the dummy app, and I get a "table already exists" error.

Everything just seems disconnected, I feel I'm missing something here to make the rspec gem work seamlessly as it usually does with full rails applications.

I followed all the changes from here http://rubyx.com/2011/03/01/start-your-engines and I can test the engine manually by launching the dummy app via the console as shown here http://railscasts.com/episodes/277-mountable-engines.

Is there a way to make rspec the default for testing a rails 3.1 engine?

Answer

dwhite picture dwhite · Sep 19, 2011

I am using RSpec with a Rails engine without issues.

I created my plugin using the following switches: -T --full --dummy-path=spec/dummy.

  • -T excludes test/unit
  • --full indicates that the plugin is an engine
  • --dummy-path is simply so that we don't get a test directory (the default is test/dummy).

From there I used the spec_helper from the "start your engines" article:

# Configure Rails Envinronment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb",  __FILE__)

require 'rspec/rails'

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

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f }

RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

For the generators. I add a config.generators block to my engine.rb file like so:

module MyEngine
  class Engine < Rails::Engine
    config.generators do |g|
      g.test_framework :rspec, :view_specs => false
    end
  end
end

With that, I'm able to get rspec tests when running a generator like the model generator.

As for the DB, is your database.yml file set up correctly? Did you load the test environment, e.g. rake db:test:clone or rake db:migrate RAILS_ENV=test? My guess is that RSpec can't see your tables because there isn't a test database set up.