我有一个模型,其方法如下:
class Post < ActiveRecord::Base
MAX_LINES = 100
MAX_POSTS = 5
def self.can_post?(user)
user.posts.count( :conditions => ["lines >= ?", MAX_LINES] ) < MAX_POSTS
end
end
用户 has_many 帖子和帖子属于_to 用户。我想为posts_exceeding_max_lines 构建测试?我正在按照FactoryGirl 自述文件创建用户并发布工厂:
FactoryGirl.define do
# post factory with a `belongs_to` association for the user
factory :post do
title "Through the Looking Glass"
user
end
# user factory without associated posts
factory :user do
name "John Doe"
# user_with_posts will create post data after the user has been created
factory :user_with_posts do
# posts_count is declared as an ignored attribute and available in
# attributes on the factory, as well as the callback via the evaluator
ignore do
posts_count 5
end
# the after(:create) yields two values; the user instance itself and the
# evaluator, which stores all values from the factory, including ignored
# attributes; `create_list`'s second argument is the number of records
# to create and we make sure the user is associated properly to the post
after(:create) do |user, evaluator|
FactoryGirl.create_list(:post, evaluator.posts_count, user: user)
end
end
end
end
在我的测试中,我使用以下方法创建用户:
new_posts_count = 5
@user = FactoryGirl.create(:user_with_posts, posts_count: new_posts_count)
但是,当我尝试打印出我有多少帖子时(使用 require 'pp'):
pp @user.posts.count
无论我的 new_posts_count 设置如何,我都得到 0。如何更改我的设置以便获得 5 个帖子的计数?