在具有0值的实例上使用每个方法时打印一次

时间:2016-03-17 23:23:58

标签: ruby-on-rails ruby-on-rails-4

我对我的帖子有一些基本评论。它可以很好地用于一个部分,即使有0个注释,也会生成一个空注释,至少它是HTML部分。

查看: posts / show.html.erb:

<% @post.comments.each do |comment| %>
   <div class="comment">
     Comment:
     <%= comment.content %> 
     <%= link_to "delete", comment, method: :delete  %>
   </div>
<% end %>

帖子控制器方法:

  def show
    @post = Post.find(params[:id])
    @comments = @post.comments
    @comment = @post.comments.build if logged_in?
  end

检查屏幕截图。请注意,注释:0,但仍打印一个空实例。

enter image description here

以下是针对此特定问题的测试:

  def setup
    @user = users(:kunok)
    @post = posts(:food)
  end

  def go_to_post(logged_in = false)
    log_in_as @user if logged_in
    get post_path @post
    assert_template 'posts/show'
  end

  test "if there is only 1 comment, there should be only 1 comment displayed" do
    go_to_post true
    assert @post.comments.count == 1 # pass
    assert_select 'div.comment', count: 1 # failure
  end

这导致了这次失败:

  

1)失败:   PostCommentsTest#test_if_there_is_only_1_comment,_there_should_be_only_1_comment_displayed [/home/kunok/dev/food-social-app/test/integration/post_comments_test.rb:29]:   预计正好1个元素匹配“div.comment”,发现2 ..   预期:1     实际:2

1 个答案:

答案 0 :(得分:2)

@post.comments.build

实际上通过在那里添加新评论来更改@ post.comments集合。您可以直接实例化新评论,以避免该问题

@comment = Comment.new