[rspec-users] Examples of writing controller specs that use authentication

Pat Maddox pergesu at gmail.com
Sat Oct 27 01:54:40 EDT 2007


On 10/26/07, Leslie Freeman <lesliefreeman3 at gmail.com> wrote:
> 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
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> 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


More information about the rspec-users mailing list