Showing posts with label Controllers. Show all posts
Showing posts with label Controllers. Show all posts

Monday, March 9, 2015

Testing with a Dummy Controller in a Rails Engine

If you have a controller in your dummy app (spec/dummy/app/controllers/dummy_controller.rb) for your Rails engine, you might need to access the list of routes within your spec code. You can do this, surprisingly, with Rails.application.routes.routes!

Thursday, February 19, 2015

Using self.included to Include Dependencies

As part of a project I'm working on, I created a mountable engine for extracting all authentication concerns for the app. I created a TestHelper module that includes methods for mocking various aspects required for authentication. These methods require Devise::TestHelpers to function properly, and my goal was for the calling app to not know or care about this dependency. To solve this, I used self.included to automatically include the helper when necessary (in my case, only in controller specs).
Here is the code:

 def self.included(receiver)  
  if defined?(receiver.metadata) && receiver.metadata[:type] == :controller  
   receiver.send :include, Devise::TestHelpers  
  end  
 end  

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 :)