2010-09-12 94 views

回答

19

沒有太多的黑客可以使用卓越的寶石:http://github.com/carlosbrando/remarkable

從顯着的文檔摘自:

describe Post do 
     it { should belong_to(:user) } 
     it { should have_many(:comments) } 
     it { should have_and_belong_to_many(:tags) } 
    end 
+0

很不錯的!我想我可能會開始使用那個寶石。 – 2010-09-13 01:13:24

+3

另一種選擇是Thoughtbot的Shoulda,它具有非常相似的語法。 http://github.com/thoughtbot/shoulda – 2010-09-13 02:00:06

+0

引人注目的看起來比Shoulda更完整。我以前沒有見過。 – 2010-09-13 02:28:37

6

您可以在類反映:

MyModel.reflect_on_association(:x).macro == :has_one 

它可能更容易,如果你只是用早該有輔助方法,所以它讀取更乾淨:it { should have_many(:x) }

1

這裏是一個RSpec獨立的解決方案,關鍵是使用reflect_on_assocation

class MyModel < ActiveRecord::Base 
    has_many :children 
    belongs_to :owner 
end 

reflection_children = MyModel.reflect_on_association(:children) 

if !reflection_children.nil? 
    if reflection_children.macro == :has_many 
    # everything is alright 
    else 
    # it's not has_many but exists 
    end 
else 
    # it doesn't exist at all ! 
end 

reflection_owner = MyModel.reflect_on_association(:owner) 

if !reflection_owner.nil? 
    if reflection_owner.macro == :belongs_to 
    # everything is alright! 
    else 
    # it's not belongs_to but exists 
    end 
else 
    # it doesn't exist at all! 
end 
相關問題