[TIP] Ensure your test data is valid

Recently I wanted to check that my test data was valid. Seems like a
reasonable thing to want to do so I thought I’d share the rake task. Add
this code to a rake file in lib/tasks and run with rake
db:fixtures:validate. It will print out the class, record id and error
messages for any model objects that fail validation.

Enjoy!
-Jonathan.

namespace :db do
namespace :fixtures do
desc “Load fixtures into the current environment’s database and
display
invalid objects”
task :validate do
Rake::Task[‘db:fixtures:load’].invoke

  Dir.glob(RAILS_ROOT + '/app/models/*.rb').each { |file| require 

file }

  Object.subclasses_of(ActiveRecord::Base).each do |klass|
    klass.find(:all).reject(&:valid?).each do |record|
      puts "#{record.class}: id=#{record.id}"
      p record.errors.full_messages
      puts
    end rescue nil
  end
end

end
end

Hello Jonathan !

2006/4/24, Jonathan V. [email protected]:

  Rake::Task['db:fixtures:load'].invoke

WARNING: db:fixtures:load loads the fixtures in the current
environment, development by default. Call using “RAILS_ENV=test” to
prevent that.

Excellent work !

Bye !

Jonathan V. wrote:

puts “#{record.class}: id=#{record.id}”

Nifty idea. Suggestion: replace your explicit use of the ‘id’ field with
the actual primary key, so it will work with classes that use a
non-default primary key.

key = record.class.primary_key.
puts “#{record.class}: #{key}=#{record.send(key.to_sym)}”


Josh S.
http://blog.hasmanythrough.com

Marcel Molina Jr. wrote:

You always have the id method as a way of accessing a record’s primary
key, regardless of what its actual column name is:

Oh yeah, I went a bit overboard. I guess I knew :id would always work,
but I blinked at the use of the hardwired “id” as the name of the key in
the output. My brain is still woozy from the conference (at which you
were greatly missed!)


Josh S.
http://blog.hasmanythrough.com

On Mon, Apr 24, 2006 at 09:56:25PM +0200, Josh S. wrote:

Jonathan V. wrote:

puts “#{record.class}: id=#{record.id}”

Nifty idea. Suggestion: replace your explicit use of the ‘id’ field with
the actual primary key, so it will work with classes that use a
non-default primary key.

key = record.class.primary_key.
puts “#{record.class}: #{key}=#{record.send(key.to_sym)}”

You always have the id method as a way of accessing a record’s primary
key,
regardless of what its actual column name is:

% cat id-is-available-regardless.rb
require ‘rubygems’
require ‘active_record’

ActiveRecord::Base.establish_connection(:adapter => ‘sqlite’, :database
=>
‘:memory:’)
ActiveRecord::Schema.define do
create_table :people, :id => false do |t|
t.column :custom_pk, :integer
t.column :name, :string
end
end

class Person < ActiveRecord::Base
set_primary_key :custom_pk
end

person = Person.create
p person.id

% ruby id-is-available-regardless.rb
– create_table(:people, {:id=>false})
-> 0.0357s
1

marcel