Examples of writing controller specs that use authentication

Hello,
I’m working on specs for a controller that handles authentication
using the restful_authentication plugin. I’m trying to find a
resource (tutorial or examples, if possible) about the best way to go
about writing mocks and specs to make sure that things like my
before_filters are working correctly. Does anyone know of any good
resources for this?

Thanks,
Les

On 10/26/07, Leslie F. [email protected] wrote:


rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

To make sure that the filter works when you’re not logged in, just
make the request:

describe CategoriesController, " POST /categories, not logged in" do
it “should redirect to the login url” do
post :create, :category => {“name” => “foo”}
response.should redirect_to(login_url)
end
end

and when you want to spec the meat of the request, stub the logged_in?
method:

describe CategoriesController, " POST /categories" do
before(:each) do
controller.stub!(:logged_in?).and_return(true)
@mock_category = mock_model(Category, :save => true)
Category.stub!(:new).and_return(@mock_category)
end

def do_post
post :create, :category => {“name” => “foo”}
end

it “should create a new category” do
Category.should_receive(:new).with(“name” =>
“foo”).and_return(@mock_category)
do_post
end

it “should save the category” do
@mock_category.should_receive(:save).and_return(true)
do_post
end

it “should redirect to the category’s url” do
do_post
response.should redirect_to(category_url(@mock_category))
end
end

Pat

On 27.10.2007, at 8.54, Pat M. wrote:

Les
it “should redirect to the login url” do
post :create, :category => {“name” => “foo”}
response.should redirect_to(login_url)
end
end

and when you want to spec the meat of the request, stub the
logged_in? method:

Or, if you need different users to behave in different ways, you
might want to create a helper in spec_helper.rb, such as this:

def login_as(user, options = {:id => “5”, :needs_activation => false,
:admin => false})
user.stub!(:id).and_return(options[:id])
user.stub!(:to_param).and_return(options[:id])
user.stub!(:needs_activation?).and_return(options
[:needs_activation])
user.stub!(:admin?).and_return(options[:admin])
controller.send :current_user=, user
end

Then you can just say this in the specs:

login_as(@user_mock_object)

and the controller will behave accordingly (assuming you use
restful_authentication/acts_as_authenticated).

//jarkko


Jarkko L.
http://jlaine.net
http://dotherightthing.com
http://www.railsecommerce.com
http://odesign.fi

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs