stantona
stantona

Reputation: 3300

Rspec redirect_to show action

I'm learning rails and have come across a problem with an Rspec. I have the following test for a controller:

describe PostsController, "creating a new post" do
  it "should redirect and show the post" do
    Post.stub!(:save).and_return(true)
    post "create"
    response.should redirect_to :action => "show"
  end
end

When I run this test I get the following failure:

PostsController creating a new post should redirect and show the post
Failure/Error: response.should redirect_to :action => "show"
ActionController::RoutingError:
  No route matches {:action=>"show", :controller=>"posts"}
  # ./spec/controllers/posts_controller_spec.rb:8:in `block (2 levels) in <top       (required)>'

Yet my when I check my routes I see my show action for my posts controller:

post GET    /posts/:id(.:format)      {:action=>"show", :controller=>"posts"}

I'm probably missing something very simple but struggling to find it.

Thanks.

Upvotes: 2

Views: 4713

Answers (3)

wawka
wawka

Reputation: 5154

You can also check redirect in shorter way. Just:

expect(response).to redirect_to assigns[:video]

Upvotes: 1

backwardm
backwardm

Reputation: 309

A quick note on the above. With version 2.13.0 of rspec-rails, the syntax I used to get this working was:

expect(response).to redirect_to(video_path(assigns[:video]))

(I was testing a create controller method for my Video model). Here's my full rspec description block for #create:

describe "POST #create" do

    context "with valid attributes" do

        it "saves the new video in the database" do
            expect{
                post :create, video: attributes_for(:video)
            }.to change(Video, :count).by(1)
        end

        it "redirects to the videos page" do
            post :create, video: attributes_for(:video)
            expect(response).to redirect_to(video_path(assigns[:video]))
        end

    end

end

Upvotes: 2

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

You forgot the id.

I usually write

response.should redirect_to(post_path(assigns[:post])

Upvotes: 12

Related Questions