次のような方法のモデルがあります。
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の投稿と投稿belongs_toユーザー。post_exceeding_max_linesのテストを作成したいですか?FactoryGirlのreadmeに従って、ユーザーを作成し、ファクトリを投稿します。
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件の投稿を取得できるように設定を変更するにはどうすればよいですか?