Skip to content

Instantly share code, notes, and snippets.

@semipermeable
Created July 14, 2011 19:18
Show Gist options
  • Save semipermeable/1083203 to your computer and use it in GitHub Desktop.
Save semipermeable/1083203 to your computer and use it in GitHub Desktop.
Rails3 Data Migration and RSpec Test
# 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
@shterrett
Copy link

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