Mark Bolusmjak
Mark Bolusmjak

Reputation: 24399

How do I find a fixture's name, given an id in Rails tests?

Rails provides a method for looking up an ID given a fixture's name:

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

Suppose, in a failing test, I'd like to print out the name of a problematic fixture given it's ID. How do I do the reverse lookup?

Upvotes: 3

Views: 1376

Answers (1)

Mark Bolusmjak
Mark Bolusmjak

Reputation: 24399

Here's some code I came up with until something better comes along. It iterates through all the loaded fixtures for a given table and returns the name if "identifies" to the given 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

Upvotes: 4

Related Questions