2013-02-14 43 views
0

我有了類似下面的方法模型:使用RSpec /水豚爲Ruby和Rails實現協會項目

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的用戶。我想爲posts_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) 

然而,當我嘗試打印出多少職位我有(與要求'pp'):

pp @user.posts.count 

我得到0,無論我的設置new_posts_count。我如何更改我的設置,以便可以計算5個帖子?

+0

看'登錄/ test.log'。它是否顯示帖子實際上正在創建? – zetetic 2013-02-15 02:53:57

回答

0
  • 不應該在用戶上定義這種方法嗎?
  • 這與工廠有什麼關係?
  • 使用可選參數,而不是一個常數

用戶的

class User < ActiveRecord::Base 
    def posts_exceeding_max_lines?(max_lines = 100, max_posts = 5) 
    posts.count(:conditions => ["lines >= ?", max_lines]) < max_posts 
    end 
end 
+0

我認爲該方法在Post中定義。 FactoryGirl創建我可用於測試帖子控制器的存根。也許我應該將測試遷移到Post模型並避免需要工廠。 – Fares 2013-02-14 20:25:26