【发布时间】:2012-10-25 03:44:10
【问题描述】:
在this 上一个问题中,我询问了如何为Post 和用户model 构建测试。我现在想测试名为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
我特别想测试comments_count:一个想在帖子中创建cmets。他们的关联已经建立(发布has_many cmets)。并检查comments_count 是否增加。
谁能给我一个测试的例子吗?
当前代码:
comment.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
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
(顺便说一句,这是我第一次在我的应用中测试一些东西。我是在测试一些不需要测试的东西吗?是否缺少一些应该测试的东西?)
【问题讨论】:
-
我对 :comment_count 很好奇。您是否有理由不使用内置查询 @post.cmets.count?
-
@new2ruby
:counter_cache => true提高性能。计数被缓存,只有一个查询何时发生变化。 -
在这一点上性能是一个重要的考虑因素吗?一直在帮助我使用 Rails 的那个人一直对我说,我不应该花时间优化可能永远不会成为问题的东西。尽管我觉得他这样做很烦人,但我还是不得不以同样的方式惹恼你。 :)
-
@KevinM Ha,好吧,如果我没有这样做,我可能会忘记将来这样做。
标签: ruby-on-rails rspec