[ ] FactoryGirl ORM |
it "supports building a PORO object" do
class User
attr_accessor :name
end
FactoryGirl.define do
factory :user do
name "Amy"
end
end
user = FactoryGirl.build(:user)
expect(user.name).to eq "Amy"
end
NoMethodError:
undefined method `save!' for #
class User
attr_reader :name
def initialize(data = {})
@name = data[:name]
end
end
NoMethodError:
undefined method `name=' for #
t "supports custom initialization" do
class User
attr_reader :name
def initialize(data)
@name = data[:name]
end
end
FactoryGirl.define do
factory :user do
name "Amy"
initialize_with { new(attributes) }
end
end
user = FactoryGirl.build(:user)
expect(user.name).to eq "Amy"
end
{
"name": "Bob",
"location": {
"city": "New York"
}
}
class Location
attr_reader :city
def initialize(data)
@city = data[:city]
end
end
class User
attr_reader :name, :location
def initialize(data)
@name = data[:name]
@location = Location.new(data[:location])
end
end
it "supports constructing nested models" do
class Location
attr_reader :city
def initialize(data)
@city = data[:city]
end
end
class User
attr_reader :name, :location
def initialize(data)
@name = data[:name]
@location = Location.new(data[:location])
end
end
FactoryGirl.define do
factory :location do
city "London"
initialize_with { new(attributes) }
end
factory :user do
name "Amy"
location { attributes_for(:location) }
initialize_with { new(attributes) }
end
end
user = FactoryGirl.build(:user)
expect(user.name).to eq "Amy"
expect(user.location.city).to eq "London"
end
puts FactoryGirl.attributes_for(:user)
# => {:name=>"Amy", :location=>{:city=>"London"}}
FactoryGirl::InvalidFactoryError: The following factories are invalid:
* user - undefined method `save!' for # (NoMethodError)
FactoryGirl.define do
factory :location do
city "London"
skip_create
initialize_with { new(attributes) }
end
factory :user do
name "Amy"
location { attributes_for(:location) }
skip_create
initialize_with { new(attributes) }
end
end
FactoryGirl.create(:user)
namespace :factory_girl do
desc "Lint factories by building"
task lint_by_build: :environment do
if Rails.env.production?
abort "Can't lint factories in production"
end
FactoryGirl.factories.each do |factory|
lint_factory(factory.name)
end
end
private
def lint_factory(factory_name)
FactoryGirl.build(factory_name)
rescue StandardError
puts "Error building factory: #{factory_name}"
raise
end
end
class User
attr_reader :name
def initialize(data)
@name = data.fetch(:name) # <-
end
end
FactoryGirl.define do
factory :user do
# name "Amy" <-
initialize_with { new(attributes) }
end
end
Error building factory: user
rake aborted!
KeyError: key not found: :name
/path/models.rb:5:in `fetch'
/path/models.rb:5:in `initialize'
/path/factories.rb:8:in `block (3 levels) in '
/path/Rakefile:15:in `lint_factory'