noizZze

RSpec and ActionController::Metal

If you like me tried to merry the two, you probably noticed they didn’t like each other. Here’s a small hack to let you test your Metal controllers. For RSpec to work with such controller, we need the following modules:

1
2
3
4
5
include ActionController::UrlFor
include ActionController::Rendering
include ActionController::Testing
include Rails.application.routes.url_helpers
include ActionController::Compatibility

Let’s assume that you have an ApiController that renders some stuff (so it already uses Rendering module). Here’s the sample api_controller.rb code:

1
2
3
4
5
6
7
class ApiController < ActionController::Metal
  include ActionController::Rendering

  def work
    render :text => { :data => 1 }.to_json
  end
end

Now, to test it you need to include all other important modules before the tests, like this (I put it inside the spec file). Here’s my sample api_controller_spec.rb file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
require 'spec_helper'

class ApiController
  include ActionController::UrlFor
  include ActionController::Testing
  include Rails.application.routes.url_helpers
  include ActionController::Compatibility
end

describe ApiController do
  it "should return content from 'work'" do
    get :work
    response.body.should == { :data => 1 }.to_json
  end
end

Hope it helps!