0

我有一个嵌套路线:

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_pathwithout@也会导致另一个错误:

ActionController::RoutingError: No route matches {:action=>"show", :controller=>"stories"}

同样的错误发生在story_path, :story_id => @story.id. 知道为什么会这样吗?

4

1 回答 1

1

我认为应该是story_path(@story.id)。见这里

于 2012-07-29T19:43:12.890 回答