Created
July 14, 2011 19:18
-
-
Save semipermeable/1083203 to your computer and use it in GitHub Desktop.
Rails3 Data Migration and RSpec Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# db/migrate/20110714024435_split_author.rb | |
class SplitAuthor < ActiveRecord::Migration | |
def self.up | |
Post.where(:author=>nil).each do |p| | |
author = Author.create!(:name => p.author_name, | |
:account_id => p.account_id) | |
p.author = author | |
p.save! | |
end | |
end | |
def self.down | |
raise ActiveRecord::IrreversibleMigration | |
end | |
end | |
# spec/migrations/split_author_spec.rb | |
require 'spec_helper' | |
require File.join(File.dirname(__FILE__), "..", "..", "db", "migrate", "20110714024435_split_author") | |
describe SplitAuthor do | |
before do | |
@posts = [] | |
@account = Factory(:account) | |
3.times do |x| | |
p = Factory.build(:post, :author=>nil, :author_name=>"author#{x}", :account=>@account) | |
p.save(:validate=>false) | |
@posts << p | |
end | |
end | |
describe "up" do | |
it "should populate authors from existing posts" do | |
expect { | |
SplitAuthor.up_without_benchmarks | |
}.to change{Author.count}.by(@posts.size) | |
Author.all.each{|x| x.account.should == @account} | |
@posts.collect(&:author).each do |a| | |
Author.find_by_name(a).should_not be_nil | |
end | |
end | |
end | |
end |
For future reference; at least as of Rails 3.2.15, running the migration is done thusly:
MigrationClass.new.up
The class must be instantiated, and the without_benchmarks
method does not exist.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
nice example.
I'm currently in the situtation much like this example where my migration is:
1.adding some columns to a table
2. migrating data
3. modifying the added columns, eg. not to accept nil
I surely want to run some tests on the data migrating code, but my worry is that once I have migrated past point 3, my tests will fail, as I cannot create test data after this point. My plan is to do something like this in the tests:
class SchemaMigration < ActiveRecord::base
end
run_migrate_data_test unless SchemaMigration.all.max > migration_point_3
any comments/pitfall on this?
regards
Lars