【发布时间】:2023-03-22 21:59:01
【问题描述】:
我正在试用 Rails 4 - 第一步 :) 我有两个带有固定装置的模型,它们之间的 HABTM 关系与匹配表 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 表中显示关联的预期结果:
<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 和其他一些断言,但似乎没有一个能够在 内部进行测试(如果我的命名有误,请纠正我) Active Record 或 Collection。我尝试使用to_s,但失败了。
如何测试我的字符串是否在book.authors 内?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 activerecord minitest