我正在使用rspec,我試圖測試我的模型y是否有許多x。我已經嘗試了各種各樣的東西,包括遍歷方法數組,並且似乎無法在線找到好方法。那我該用什麼?如何在Rails中測試belongs_to和has_many?
8
A
回答
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
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
相關問題
- 1. Rails 3中的belongs_to和has_many
- 2. Rails has_many belongs_to associations
- 3. 如何在rails中跨越belongs_to和has_many關係?
- 4. Rails的,的has_many,belongs_to的
- 5. Rails has_many/belongs_to不工作
- 6. Rails belongs_to和has_many關係問題
- 7. Rails has_many和belongs_to方法的關係
- 8. 的Rails belongs_to的測試
- 9. Rails 5.0.2 - 關係中的ID belongs_to/has_many
- 10. Rails 3 ActiveAdmin。如何用不同的外鍵設置has_many和belongs_to?
- 11. 如何正確使用belongs_to和has_many?
- 12. 如何在數據庫中反映Ruby on Rails中新的belongs_to和has_many關係
- 13. 在Rails中,使用「has_many with belongs_to」和「has_many with has_one」有什麼區別?
- 14. 如何在Rails 4.2中創建一個名爲has_many和belongs_to的關聯?
- 15. 如何在rails中通過和belongs_to關聯執行has_many的連接表?
- 16. has_many和其他字段belongs_to
- 17. 的has_many和belongs_to的不
- 18. 兩層has_many/belongs_to
- 19. Rails:使用has_many/belongs_to關係的順序
- 20. Rails的模型的has_many,belongs_to的關係
- 21. Rails 2.3.8關聯問題has_many belongs_to
- 22. 如何在Mongoid中獲得has_many belongs_to關係的總和?
- 23. Ruby on Rails的:belongs_to的和的has_many了在同一個模型
- 24. Rails的協會職務和地點 - 的has_many和belongs_to的
- 25. Ruby中has_many和belongs_to的等價關係
- 26. 測試存在和belongs_to與Rspec
- 27. Rails RSpec測試has_many:通過關係
- 28. 在rails中命名has_many/belongs_to關聯失敗
- 29. has_many,belongs_to association has_many關聯模型在belongs_to中有兩個別名fk associated_model
- 30. Rails的STI的has_many和belongs_to的繼續尋找類列
很不錯的!我想我可能會開始使用那個寶石。 – 2010-09-13 01:13:24
另一種選擇是Thoughtbot的Shoulda,它具有非常相似的語法。 http://github.com/thoughtbot/shoulda – 2010-09-13 02:00:06
引人注目的看起來比Shoulda更完整。我以前沒有見過。 – 2010-09-13 02:28:37