Rspec redirect_to显示操作

时间:2011-05-26 14:07:12

标签: ruby-on-rails rspec2

我正在学习rails并且遇到了Rspec的问题。我对控制器进行了以下测试:

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

当我运行此测试时,我遇到以下故障:

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)>'

然而,当我检查我的路线时,我看到我的帖子控制器的显示动作:

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

我可能错过了一些非常简单但很难找到的东西。

感谢。

3 个答案:

答案 0 :(得分:11)

您忘记了id

我经常写

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

答案 1 :(得分:2)

关于上述内容的快速说明。对于版本2.13.0的rspec-rails,我用来实现这个工作的语法是:

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

(我正在测试我的视频模型的创建控制器方法)。这是#create的完整rspec描述块:

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

答案 2 :(得分:1)

您还可以更短的方式检查重定向。只是:

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