在功能测试中测试嵌套路由

时间:2012-07-29 19:27:25

标签: ruby-on-rails ruby-on-rails-3

我有一个嵌套路线:

resources :stories do
  resources :comments
end

这是我在控制器中的创建方法:

def create
  @story = Story.find(params[:story_id])
  @comment = @story.comments.build(params[:comment])
  @comments = @story.comments.all

  respond_to do |format|
    if @comment.save
      format.html { redirect_to @story, notice: t('controllers.comments.create.flash.success') }
      format.json { render json: @comment, status: :created, location: @comment }
    else
      format.html { render template: "stories/show" }
      format.json { render json: @comment.errors, status: :unprocessable_entity }
    end
  end
end

这是测试:

setup do
  @comment = comments(:one)
  @story = stories(:one)
end

  ....

test "should create comment" do
  assert_difference('Comment.count') do
    post :create, :story_id => @story.id, comment: { content: @comment.content, name: @comment.name, email: @comment.email }
  end

  assert_redirected_to @story_path
end

最终会出现此错误:

1) Failure:
test_should_create_comment(CommentsControllerTest) [/home/arach/workspace/Web/ruby/nerdnews/test/functional/comments_controller_test.rb:25]:
Expected response to be a redirect to <http://test.host/stories/980190962/comments> but was a redirect to <http://test.host/stories/980190962>

我不知道为什么测试期望重定向到stories/:id/comments。我尝试了story_comment_path之类的其他东西,但它也没有帮助。没有story_path的{​​{1}}也会出现另一个错误:

@

ActionController::RoutingError: No route matches {:action=>"show", :controller=>"stories"} 发生同样的错误。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

我认为它应该是story_path(@ story.id)。请参阅here