在Rails测试中给出一个id,如何找到夹具的名称?

时间:2015-09-01 01:37:01

标签: ruby-on-rails testing fixtures

Rails提供了一种在给定灯具名称的情况下查找ID的方法:

参见[ActiveRecord :: FixtureSet.identify](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html#method-c-identify

假设在测试失败的情况下,我想打印出有问题的灯具的名称,并给出它的ID。我该如何进行反向查找?

1 个答案:

答案 0 :(得分:2)

这是我提出的一些代码,直到有更好的方法出现。它遍历给定表的所有加载的fixture并返回名称,如果“识别”给定的id。

class ActiveRecord::FixtureSet
  def self.reverse_lookup(table, id)
    ActiveRecord::FixtureSet.all_loaded_fixtures[table.to_s].each do |key, _|
      return key if ActiveRecord::FixtureSet.identify(key) == id
    end
    nil
  end
end
相关问题