Monday, January 26, 2015

Testing Controllers in Rails Engines

Testing your controllers in a Rails engine requires just a few extra steps compared to testing in a Rails application.

For example, you're working on an engine called Animals, and you have a BearsController with an index action that returns all the bears you've registered.

With a controller like this:
 // app/controllers/animals/bears_controller.rb  
 module Animals  
   class BearsController < ApplicationController  
     def index  
       // return all bears  
     end  
   end  
 end  
and a routes file like this:
 // config/routes.rb  
 Animals::Engine.routes.draw do  
   get '/index' => 'bears#index'  
 end  
you will need to update your dummy routes file to look like this:
 // spec/dummy/config/routes.rb  
 Rails.application.routes.draw do  
   mount Animals::Engine => "/animals"  
 end  
and in your controller spec you will need to add one extra line compared to normal:
 // spec/controllers/animals/bears_controller_spec.rb  
 RSpec.describe BearsController do  
   // this is the key line!  
   routes { Animals::Engine.routes }
  
   describe 'GET :index' do  
     it 'does the thing' do  
       get :index
       // test that all bears are returned  
     end  
   end  
 end  
and now your controller test will go to the appropriate routes :)

No comments:

Post a Comment