【问题标题】:Testing the controller of a comment that belongs to a post in Rails在 Rails 中测试属于帖子的评论的控制器
【发布时间】:2013-06-09 15:35:41
【问题描述】:

我对 Rails 很陌生,我对 Ruby 的了解也很生疏。无论如何,我正在尝试以正确的方式编写我的第一个 Rails 应用程序,并具有良好的测试覆盖率。我一直在尝试遵循getting started 指南并将其与testing 指南相结合来完成此任务。 (为什么这两件事没有结合起来!?)

所以,现在我一直在尝试向Comments 控制器添加方法:

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end

这是我的测试结果:

class CommentsControllerTest < ActionController::TestCase  
  setup do
    @comment = comments(:one)
  end
  test "should create comment" do
    assert_difference('Comment.count') do
      post :create, comment: { body: @comment.body, commenter: @comment.commenter, ???? }
    end

    assert_redirected_to post_path(assigns(:post)) #???? 
  end
end

用这个夹具

one:
  commenter: mystring
  body: mytext
  post: 

two:
  commenter: mystring
  body: mytext
  post: 

我的问题是我看不到如何以惯用的 Rails 方式创建和引用 Post 作为评论的父级。

我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    您需要在创建请求中添加一个参数post_id(此post_id 由控制器中的@post = Post.find(params[:post_id]) 行使用)。示例:

    class CommentsControllerTest < ActionController::TestCase  
    
      setup do
        @comment = comments(:one)
        @post = posts(:post_one)
      end
    
      test "should create comment" do
        assert_difference('Comment.count') do
          post :create, comment: { body: @comment.body, commenter: @comment.commenter }, post_id: @post.id
        end    
        assert_redirected_to post_path(assigns(:post))
      end
    
    end
    

    此代码假定您已在您的固定装置中定义了由:post_one 标识的Post

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2021-10-02
      • 2014-06-11
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2016-07-26
      相关资源
      最近更新 更多