Skip to content

Instantly share code, notes, and snippets.

@danini-the-panini
Last active August 7, 2020 15:24
Show Gist options
  • Save danini-the-panini/0fc858c67a19e57b39d833c12b8244b1 to your computer and use it in GitHub Desktop.
Save danini-the-panini/0fc858c67a19e57b39d833c12b8244b1 to your computer and use it in GitHub Desktop.
Rails Fixtures Test

Test validity of all your fixtures in one simple test.

Just put this file somewhere, like maybe test/models, and run bin/rails test test/models/fixture_test.rb.

Even gives you the line number of the fixture definition in the failure message!

require 'test_helper'
class FixturesTest < ActiveSupport::TestCase
Dir.glob(Rails.root.join('test', 'fixtures', '*.yml')).each do |filename|
set_name = File.basename(filename, '.yml')
test "#{set_name} fixtures are valid" do
ActiveRecord::FixtureSet.all_loaded_fixtures[set_name].each do |fixture_name, fixture|
value = fixture.find
unless value.valid?
line_number = File.read(filename).each_line.find_index { |l| l.chomp.match?(/\A#{fixture_name}:\z/) } + 1
fail "#{filename}:#{line_number}: #{value.errors.full_messages.to_sentence}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment