2016-03-01 29 views
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

回答

1

對於你上面嘗試已經給出的例子:

author_array = ['John Doe', 'Mary Jane'] 
book.authors.each do |author| 
    assert_equal true, author_array.include?(author.name) 
end 

通過作者的每個作者這將循環並檢查author.name是author_array內

authors_names = '' 
book.authors.each{ |author| authors_names + author.name + " "} 
assert_equal "John Doe Mary Jane", authors_names.chomp 

這會給你是一個字符串,用空格隔開每個名字並刪除尾部空格。它仍然需要你迭代兩個作者對象。

+0

謝謝。這會做,但有點多少,因爲我認爲:)是否沒有辦法從'book.authors'的結果產生一個字符串? –

+0

什麼是返回給你的基本上是一個包含兩個作者對象的數組,因此需要某種形式的迭代,你可以這樣做我想: – SickLickWill

+1

最簡潔的解決方案是使用委託。然後你可以調用book.authors_name。這涉及到模型的一些重構,但如果你感興趣,這裏有一個鏈接[http://vaidehijoshi.github.io/blog/2015/03/31/delegating-all-of-the-things-with-ruby-可轉發/] – SickLickWill

相關問題