【问题标题】:Rails 4: Assert strings in ActiveRecord/fixture with minitestRails 4:使用 minitest 在 ActiveRecord/fixture 中断言字符串
【发布时间】: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


    【解决方案1】:

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

    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
    

    这将为您提供一个字符串,用空格分隔每个名称并删除尾随空格。不过,它仍然需要您遍历两个作者对象。

    【讨论】:

    • 谢谢。这会做,但不知何故有点像我想的:) 有没有办法从book.authors 的结果中创建一个字符串?
    • 返回给你的基本上是一个包含两个作者对象的数组,所以需要某种形式的迭代,我想你可以这样做:
    • 最干净的解决方案是使用委托。然后你可以调用 book.authors_name。这涉及到模型的一些重构,如果你有兴趣,这里有一个链接 [vaidehijoshi.github.io/blog/2015/03/31/…
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多