2011-06-08 76 views
0

我正在使用MongoMapper而不是ActiveRecord。rspec測試與多態類的問題

我有一個用戶模型和一個任務模型。 任務模型中,我有2個屬性如下:

  • 所有者
  • 作者

兩個屬性是用戶參考。

下面是這兩個模型之間的關係:

User.rb

has_many :tasks, :as => :owner 

Taks.rb

belongs_to :owner, :class_name => "User", :polymorphic => true 

我用RSpec的編寫測試: (@user之前申報)

it "should have many tasks" do 
    another_user = Factory.create(:user, :email => Faker::Internet.email) 

    task_1 = Factory.create(:task, :owner => another_user, :author => another_user) 
    task_2 = Factory.create(:task, :owner => another_user, :author => @user) 
    task_3 = Factory.create(:task, :owner => @user, :author => @user) 

    another_user.tasks.size.should == 2 
end 

這裏是問題:

Failure/Error: another_user.tasks.size.should == 2 
expected: 2 
got: 3 (using ==) 

但是當我做在軌控制檯一樣,我取得好成績......

這裏是工廠:

Factory.define :user do |u| 
    u.first_name 'Test User'       # 
    u.username 'Test User'       # 
    u.surname 'TheTest'        # 
    u.email '[email protected]'       # 
    u.password 'please'        # 
    u.confirmed_at Time.now       # 
end 

Factory.define :task do |u| 
    u.author nil          # 
    u.owner nil          # 
    u.subjects [] 
    u.timeframe "" 
    u.initially_placed_at nil 
    u.label "Foo Task"        # 
    u.description "A small task description" 
    u.done false 
    u.pinned false 
    u.confidentiality "" 
end 

回答

0

有幾個答案:

1)您可能有這個天賦之前運行的泄漏規範(這意味着一個任務與「another_user」之前的ID和類型創建這

2)可能需要創建任務,太(嘗試使用Factory.create(:任務),而不是僅僅廠(:任務)

3)您可能想看看shoulda,它可以幫助你符合規範協會很容易,像這樣的例子:

它{應當have_many(:職位)}

+0

泄漏規範似乎是完全不可能的(鏈接在ID上,該項目剛創建,...),並且'Factory.create(:task)'和'Factory(:task)'沒有區別' 。但是,應該確實是一個很好的提示! – nathanvda 2011-06-08 10:13:33

+0

Thx爲答案,我使用mongo,我已經照顧應該,我不能用它來檢查關聯。但是,我會嘗試你說的其他事情。 – 2011-06-08 12:15:18

+0

我已更新我的帖子,可以查看嗎? – 2011-06-08 12:25:08

0

,這是非常令人麻木確實如此。我看到幾個選項,以幫助您找到此:

  • 使用的RubyMine,在那裏你可以很容易地調試測試

  • 增添了不少日誌報表

  • 添加下面的測試:

    another_user.tasks.should =〜[任務1,任務2]

這將顯示項目列表中的差異,並且另一項是task3

  • 我希望您的工廠不會爲每個用戶創建默認任務?

除此之外:的確,結賬shoulda