ruby-on-rails - 测试属于 Rails 中帖子的评论的 Controller

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

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

所以,现在我一直在尝试测试向 Comments Controller 添加一个方法:

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 作为评论的父级。

我该怎么做?

最佳答案

你需要在创建请求中添加一个参数post_id(这个post_id@post = Post.find(params[:post_id ]) 在 Controller 中)。示例:

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

关于ruby-on-rails - 测试属于 Rails 中帖子的评论的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17011224/

相关文章:

ruby-on-rails - Ruby on Rails : singular resource and form_for

ruby-on-rails - Ruby:使用 google-api-ruby-client SDK 将文件上传到 Google 驱动器失败并出现 Timeout::Error

ruby-on-rails - 找不到 ruby

ruby-on-rails - 'merge' :String - Rails 3. 1 的未定义方法 "test"

ruby-on-rails-3 - 如何在助手的子类中捕获 block ?

ruby-on-rails - Rails 开发效率 - 顶级 Textmate 快捷方式

ruby-on-rails - 在 ubuntu 13.04 中安装交互式 Ruby shell 和 ruby​​ 时遇到困难并开始使用 rails

ruby-on-rails-3 - 使用 jquery tokeninput 和 acts_as_taggable_on

ruby-on-rails - bcrypt 的盐发生了什么变化?

ruby - 如何只允许 Ruby 函数中的参数为特定类型?