Skip to content

Instantly share code, notes, and snippets.

@mataki
Created June 5, 2013 05:36
Show Gist options
  • Save mataki/5711817 to your computer and use it in GitHub Desktop.
Save mataki/5711817 to your computer and use it in GitHub Desktop.
factory girl は mass assignment を回避してデータを作れるか? YES
require "active_record"
require "sqlite3"
ActiveRecord::Base.configurations = {'test' => {:adapter => 'sqlite3', :database => ':memory:'}}
ActiveRecord::Base.establish_connection('test')
class CreateAllTables < ActiveRecord::Migration
def self.up
create_table :locales do |t|
t.string :name
t.integer :key
end
end
end
CreateAllTables.up
class Locale < ActiveRecord::Base
attr_accessible :name
validates :name, presence: true
validates :key, presence: true
end
u = Locale.new(name: "name", key: 10)
u.save
u.errors.full_messages # => ["Key can't be blank"]
require "factory_girl"
FactoryGirl.define do
factory :locale do
name "Akihiro Matsumura"
key 29
end
end
fu = FactoryGirl.create(:locale)
fu.valid? # => true
fu.attributes # => {"id"=>1, "name"=>"Akihiro Matsumura", "key"=>29}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment