Rails 4:使用 minitest 断言 ActiveRecord/fixture 中的字符串

Rails 4: Assert strings in ActiveRecord/fixture with minitest

我正在尝试 Rails 4 - 第一步 :) 我有两个带有固定装置的模型,它们之间的 HABTM 关系与匹配 table authors_books。所有设置和 运行 都很好。

现在我想测试一个字符串(作者姓名)是否存在。我正在使用 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 中关联的预期结果 table:

<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 和其他一些断言,但是 none 似乎能够在 内部进行测试(如果我的命名有误请纠正我) 活动记录或集合。我尝试使用 to_s 但失败了。

如何测试我的字符串是否在 book.authors 内?

对于上面给出的示例,请尝试:

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

这将遍历 authors 中的每个作者并检查 author.name 是否在 author_array

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

这将为您提供一个字符串,用 space 分隔每个名称并删除结尾的 space。不过,它仍然需要您遍历两个 authors 对象。