2010-10-19 111 views
19

我是新來的測試和rails,但我試圖讓我的TDD過程正常。Rails RSpec測試has_many:通過關係

我想知道你是否使用任何種類的範例來測試has_many:通過關係? (或只是has_many一般我想)。

例如,我發現在我的模型規範中,我絕對編寫簡單的測試來檢查關係方法的兩端關係。

即:

require 'spec_helper' 

describe Post do 

    before(:each) do 
    @attr = { :subject => "f00 Post Subject", :content => "8ar Post Body Content" } 
    end 

    describe "validations" do 
    ...  
    end 

    describe "categorized posts" do 

    before(:each) do 
     @post = Post.create!(@attr) 
    end 

    it "should have a categories method" do 
     @post.should respond_to(:categories) 
    end 

    end 

end 

然後在我的類別符合規範我做逆測試和檢查@ category.posts

我失去了還有什麼?謝謝!!

回答

47

我建議您查看名爲Shoulda的寶石。它有很多宏來測試關係和驗證等事情。

如果你想要的是測試的的has_many關係存在,那麼你可以做到以下幾點:

describe Post do 
    it { should have_many(:categories) } 
end 

或者,如果你正在測試的has_many:通過,那麼你會使用這樣的:

describe Post do 
    it { should have_many(:categories).through(:other_model) } 
end 

我覺得Shoulda Rdoc也很有幫助。

+0

在那裏你進行測試時,親手做任何共同的東西?我正在尋找基本的東西,我應該馬上開始做。諸如......測試我的關聯似乎是合理的,但是我應該通過關聯測試每種方法嗎?或者如何知道何時停止?大聲笑 – 2010-10-20 05:36:59

+0

我真的很喜歡使用這些快速單行測試,因爲它們非常易於安裝。我總是從這些開始,並添加每個關係和驗證,包括所有直通關聯。它不需要太多工作,也不會增加測試的開銷。然後,當我添加功能時,我會添加更多的單元測試。如果您在編寫代碼時爲模型編寫測試,這確實會迫使您編寫簡單的模塊化代碼。 – 2010-10-20 12:05:36

+0

如何通過與syntex的關聯來編寫has_many? – indb 2016-02-17 13:20:57

1

remarkable會做到這一點很好:

describe Pricing do 

    should_have_many :accounts, :through => :account_pricings 
    should_have_many :account_pricings 
    should_have_many :job_profiles, :through => :job_profile_pricings 
    should_have_many :job_profile_pricings 

end 

一般來說,你只需複製所有的關係,從模型的規範,改變「有」到「should_have」,「belongs_to的」到「should_belong_to」等等。爲了回答測試欄的費用問題,它還會檢查數據庫,確保該關聯正常工作。

宏還包括用於檢查驗證,以及:

should_validate_numericality_of :amount, :greater_than_or_equal_to => 0 
+0

非凡的聲音很酷!你用的是rails3 env嗎? – 2010-10-20 20:36:49

+0

@Zaz,到目前爲止我已經使用Rails 2.2.3和2.3.9。我相信它也適用於Rails 3,但我沒有嘗試過。 – 2010-10-21 01:59:35

2
describe "when Book.new is called" do 
    before(:each) do 
    @book = Book.new 
    end 

    #otm 
    it "should be ok with an associated publisher" do 
    @book.publisher = Publisher.new 
    @book.should have(:no).errors_on(:publisher) 
    end 

    it "should have an associated publisher" do 
    @book.should have_at_least(1).error_on(:publisher) 
    end 

    #mtm 
    it "should be ok with at least one associated author" do 
    @book.authors.build 
    @book.should have(:no).errors_on(:authors) 
    end 

    it "should have at least one associated author" do 
    @book.should have_at_least(1).error_on(:authors) 
    end 

end