0
我正在嘗試Rails 4 - 第一步:)我有兩個模型與燈具和他們之間的HABTM關係與匹配的表authors_books
。所有的設置和運行都很好。Rails 4:ActiveRecord中的斷言字符串/最小的燈具
現在我想測試一個字符串(作者姓名)的存在。我正在使用Minitest。
筆者型號:
class Author < ActiveRecord::Base
has_and_belongs_to_many :books
end
書型號:
class Book < ActiveRecord::Base
has_and_belongs_to_many :authors
end
測試:
test "fixture book has authors" do
book = books(:book_one)
# check for correct count
assert_equal 2, book.authors.count
# test for existence of "John" and "Mary" inside book.authors
...
end
當我使用throw book.authors.inspect
,它顯示了在the authors_books
表的關聯預期的結果:
<ActiveRecord::Associations::CollectionProxy [#<Author id: 455823999, name: "John Doe", created_at: "2016-03-01 15:07:32", updated_at: "2016-03-01 15:07:32">, #<Author id: 814571245, name: "Mary Jane", created_at: "2016-03-01 15:07:32", updated_at: "2016-03-01 15:07:32">]>
我嘗試使用assert_match
和其他一些斷言,但沒有一個似乎能夠在(糾正我,如果我錯了,與命名請)活動記錄或集合內部測試。我試圖使用to_s
但失敗。
如何測試我的字符串是否在book.authors
?
謝謝。這會做,但有點多少,因爲我認爲:)是否沒有辦法從'book.authors'的結果產生一個字符串? –
什麼是返回給你的基本上是一個包含兩個作者對象的數組,因此需要某種形式的迭代,你可以這樣做我想: – SickLickWill
最簡潔的解決方案是使用委託。然後你可以調用book.authors_name。這涉及到模型的一些重構,但如果你感興趣,這裏有一個鏈接[http://vaidehijoshi.github.io/blog/2015/03/31/delegating-all-of-the-things-with-ruby-可轉發/] – SickLickWill