在上一个问题中,我询问了如何为 aPost
和 User构建测试model
。我现在想测试第三个模型,称为Comment
.
架构.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
我特别想测试comments_count
:一个想在帖子中创建评论。他们的关联已经建立(发表has_many
评论)。并检查是否comments_count
增加。
谁能给我一个测试的样子的例子吗?
当前代码:
评论.rb:
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :post, :counter_cache => true
belongs_to :user
end
规格/工厂:
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
规格/模型/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
(顺便说一句,这是我第一次在我的应用程序中测试一些东西。我在测试一些不需要测试的东西吗?是否缺少一些应该的东西?)