Using Shoulda redirect_to to test a controller's create action

1.1k views Asked by At

I'm using RSpec + Shoulda to test my RESTful controller in Rails 3. I'm having trouble figuring out how to test the create action's redirect. The standard RESTful controller should redirect to the show action for the new post. For example, if I have a ProjectsController for a Project model, then upon successful create, that action should:

redirect_to project_url(@project)

Shoulda provides a handy redirects_to macro for handling this. Here is what I have tried:

describe ProjectsController, '#create' do
  context "Anonymous user" do
    before :each do
      @attrs = Factory.attributes_for(:project_with_image)
      post :create, :project => @attrs
    end
    it { should assign_to(:project) }
    it { should respond_with(:redirect) }
    it { should redirect_to(@project) }
  end
end

(Yes, I'm using FactoryGirl, but since I'm only using it for attributes in this case, it shouldn't matter. I think.)

How do I specify the last test there? It should redirect_to(...) what? I've tried @project, project_url(@project).. But I can't figure it out.

Looking at the Shoulda matcher code, I noticed that the redirect_to matcher can accept a block. But I'm not sure how to access the newly created @project object in that block...

Any thoughts?

1

There are 1 answers

1
iGEL On BEST ANSWER

Haven't tried it, but the problem probably is, that @project is not available in your spec. How about

it {should redirect_to(Project.last) }
or
it {should redirect_to(assigns(:project)) }
?