I'm writing a test to check that if a reply is posted to a comment, the original comments amount of replies is indeed increased by one. Sounds pretty simple... but somehow my second assert_difference is not seeing the required increase.
Relevant part of the model:
# User.erb
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
belongs_to :comment_parent, class_name: "Comment", foreign_key: "comment_id"
has_many :replies, class_name: "Comment", foreign_key: "comment_id", dependent: :destroy
end
And the Unit test:
# model_test.erb
test 'If new comment is created as reply to a comment, their count increases by one' do
comment_one = @post.comments.build(content: 'test', user_id: 1)
assert_difference 'Comment.count', 1 do
comment_one.save()
end
comment_two = comment_one.replies.build(comment_id: comment_one.id, content: 'test', user_id: 1, commentable: Post.new)
assert_difference comment_one.replies.count.to_s, 1 do
comment_two.save()
end
end
I've also adapted the second assert_difference to check if the second comment indeed saves, which validates. So somehow the call to comment_one.replies in the assert_difference tag is not updated by the save of the comment_two or is evaluated before the block runs.
Any thoughts on a fix? Any other tips (or links) for writing succesfull (Rails) unit tests are also more then welcome!
Aucun commentaire:
Enregistrer un commentaire