在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
:想要在帖子中创建评论。他们之间的联系已经完成(has_many
评论后)。并检查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
规格/模型/ 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
(顺便说一下,这是我第一次在我的应用程序中测试一些东西。我是否在测试一些不需要测试的东西?是否有遗漏的东西应该?)
答案 0 :(得分:2)
我们可能需要工厂征求意见:
FactoryGirl.define do
factory :comment do
content "Sample comemnt"
association :user
association :post
end
end
以下测试(我在请求测试中添加)将检查以确保在用户向表单添加内容并单击右键时实际添加了注释:
describe "New comments" do
let(:post) FactoryGirl.create(:post)
let(:user) FactoryGirl.create(:user)
context "valid with content comment added to database" do
before do
visit post_path(post)
fill_in 'Content', with: "A new comment."
end
expect { click_button 'Create Comment' }.to change(Comment, :count).by(1)
end
end
此测试可能适用于评论模型规范:
describe Comment do
let(:comment) { FactoryGirl.create(:comment) }
subject { comment }
it { should respond_to(:content) }
it { should respond_to(:user_id) }
it { should respond_to(:user) }
it { should respond_to(:post_id) }
it { should be_valid }
it "should belong to a post which has a comment count of 1" do
comment.post.comment_count.should equal 1
end
end
然后进行此测试传递的方法是在注释模型中放置一些内容,以便在创建新注释时更新它所属的帖子中的comment_count属性。
我不是100%确定最后一次测试是否正确写入。我不确定你是否可以覆盖之前定义的主题。