views:

63

answers:

3

I have an application that detects the subdomain on a request and sets the result to a variable.

e.g.

before_filter :get_trust_from_subdomain

def get_trust_from_subdomain
  @selected_trust = "test"
end

How can I test this with Test::Unit / Shoulda? I don't see a way of getting into ApplicationController and seeing what's set...

+1  A: 

The assigns method should allow you to query the value of @selected_trust. To assert that its value equals "test" as follows:

assert_equal 'test', assigns('selected_trust')

Given a controller foo_controller.rb

class FooController < ApplicationController
  before_filter :get_trust_from_subdomain

  def get_trust_from_subdomain
    @selected_trust = "test"
  end

  def index
    render :text => 'Hello world'
  end
end

one might write a functional test as follows in foo_controller_test.rb:

class FooControllerTest < ActionController::TestCase
  def test_index
    get :index
    assert @response.body.include?('Hello world')
    assert_equal 'test', assigns('selected_trust')
  end
end

Related to comment: note that the filter can be placed in ApplicationController and then any derived controller will also inherit this filter behaviour:

class ApplicationController < ActionController::Base
  before_filter :get_trust_from_subdomain

  def get_trust_from_subdomain
    @selected_trust = "test"
  end
end

class FooController < ApplicationController
  # get_trust_from_subdomain filter will run before this action.
  def index
    render :text => 'Hello world'
  end
end
Richard Cook
The before_filter is in my application controller - or are you suggesting that I setup a controller specifically for this test?
Neil Middleton
Not at all. You can put the filter directly in `ApplicationController` and the test should work just the same. `FooController` is just an illustrative example. Furthermore any controller that subclasses `ApplicationController` directly or indirectly will inherit this filter behaviour and you can test it in any related controller functional test.
Richard Cook
A: 

ApplicationController is global, have you considered writing a Rack Middleware instead? Way easier to test.

Tass
A: 

I've opted for this in another controller in the application:

require 'test_helper'

class HomeControllerTest < ActionController::TestCase

  fast_context 'a GET to :index' do
    setup do
      Factory :trust
      get :index
    end
    should respond_with :success

    should 'set the trust correctly' do
      assert_equal 'test', assigns(:selected_trust)
    end
  end

end
Neil Middleton