Repository navigation
How To: Controllers and Views tests with Rails 3 (and rspec)
First, be sure to speed up your tests!
Also, the examples above are also valid for Test::Unit, just replace the before(:each) callbacks syntax from RSpec by the setup callbacks from Test::Unit.
Controller specs won’t work out of the box if you’re using any of devise’s utility methods.
As of rspec-rails-2.0.0 and devise-1.1, the best way to put devise in your specs is simply to add the following into spec_helper:
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
endI also like to write controller_macros.rb file which contains the following:
module ControllerMacros
def login_admin
before(:each) do
build :admin # Using blueprints gem for fixtures data
@request.env["devise.mapping"] = :admin
sign_in @admin
end
end
endor if you’re using factory_girl:
module ControllerMacros
def login_admin
before(:each) do
@request.env["devise.mapping"] = :admin
sign_in Factory.create(:admin)
end
end
endThen in spec_helper:
RSpec.configure do |config|
config.extend ControllerMacros, :type => :controller
endSo now in my controller specs I can now do:
describe MyController do
login_admin
it "should get index" do
get 'index'
response.should be_success
end
endFor RSpec2 view tests with Rails3 you may need to stub out the “resource” and “resource_name” methods in @view to return the information for the model you’re using, and also stub out the “devise_mapping” method to return Devise.mappings. Here’s an example view test for devise/sessions/new.html.erb where Devise is configured to use the “User” model:
spec/views/devise/sessions/new.html.erb_spec.rb:
require 'spec_helper'
require 'devise/test_helpers'
describe "devise/sessions/new.html.erb" do
let(:user) do
stub_model(User).as_new_record
end
before do
assign(:user, user)
# Devise provides resource and resource_name helpers and
# mappings so stub them here.
@view.stub(:resource).and_return(user)
@view.stub(:resource_name).and_return('user')
@view.stub(:devise_mapping).and_return(Devise.mappings[:user])
end
it "renders a form to sign the user in" do
render
rendered.should have_selector("form",
:method => "post",
:action => user_session_path
) do |form|
form.should have_selector("input", :type => "submit")
end
end
end