In this previous question I asked how to build a test for a Post
and User model
. I would like to now test a third model called Comment
.
schema.rb:
create_table "posts", :force => true do |t|
t.string "title"
t.string "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "comments_count", :default => 0, :null => false
t.datetime "published_at"
t.boolean "draft", :default => false
end
create_table "comments", :force => true do |t|
t.text "content"
t.integer "post_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
I specially want to test the comments_count
: a want to create comments in a post. Their association had been already made (post has_many
comments). and check if comments_count
increases.
Can anyone give me an example of how the test would look like?
Current code:
comment.rb:
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :post, :counter_cache => true
belongs_to :user
end
spec/factories:
FactoryGirl.define do
factory :user do
username "Michael Hartl"
email "michael@example.com"
password "foobar"
password_confirmation "foobar"
end
end
FactoryGirl.define do
factory :post do
title "Sample Title"
content "Sample Content"
published_at Time.now()
comments_count 0
draft false
association :user
end
end
spec/models/post_spec.rb:
require 'spec_helper'
describe Post do
let(:post) { FactoryGirl.create(:post) }
subject { post }
it { should respond_to(:title) }
it { should respond_to(:content) }
it { should respond_to(:user_id) }
it { should respond_to(:user) }
it { should respond_to(:published_at) }
it { should respond_to(:draft) }
it { should respond_to(:comments_count) }
its(:draft) { should == false }
it { should be_valid }
end
(By the way, this is my first time testing something in my app. Am I testing something that doesn't need testing? Is there something missing that should?)