0

一个问题中,我询问了如何为 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

(顺便说一句,这是我第一次在我的应用程序中测试一些东西。我在测试一些不需要测试的东西吗?是否缺少一些应该的东西?)

4

1 回答 1

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% 确定那里的最后一个测试是否正确编写。我不确定您是否可以覆盖先前定义的主题。

于 2012-10-25T07:53:48.667 回答