How to Use Factorygirl to Create an Attribute Called "Alias"

How to use FactoryGirl to create an attribute called alias?

Ruby doesn't know whether you're trying to call a method called alias or alias one method as another, and defaults to the latter. You can disambiguate by doing

self.alias "dummy"

ie, by explicitly specifying the receiver. This is usually the way to go in other cases where it is ambiguous whether you are calling a method or doing something else e.g.

self.foo = 'bar'

to call the foo= method rather than create a local variable called foo.

For a small number of field names this won't work. Factory girl's DSL uses method_missing so if the DSL object has a method of that name it will be called instead. In those cases you can do what the DSL sugar normal does for you and call add_attribute directly:

FactoryGirl.define do
factory :blah do
add_attribute :name, "some value"
end
end

is the same as

FactoryGirl.define do
factory :blah do
name "some value"
end
end

What's happen that _id attribute in FactoryGirl?

I think it might be important for ActiveRecord.

If you don't want that behavior you might do some monkey patching:

module FactoryGirl
self.aliases = []
end

FactoryGirl define attribute by calling method on another factory

For the latest version of FactoryGirl, use association to map to other ActiveRecord Models:

factory :job do
# ...
association :assignee, factory: :user
end

This is straight from the docs.


From the error you posted, it is stating you are trying to get the user.id but user is not an ActiveRecord instance but a proxy from FactoryGirl. You will not get this error if you are using the association method. If you need to directly access a model, you have to manually build it first. You can do this by passing a block in your factory:

factory :job do
assignee_id { FactoryGirl.create(:user).id }
end

It looks like you are trying to associate the same model twice, for this you can use before_create callback to create a User model and assign to user and assignee:

factory :job do

before(:create) do |job|
user = FactoryGirl.create(:user)
job.assignee = user
job.user = user
end
end

Override attributes keys in FactoryGirl

How about changing your :post factory:

factory :post do
published { Time.now }
# published_at
end

Or, if you want to separate API and Web based posts, create a new factory:

factory :api_post, class: Post do
...
end

Call trait from another trait with params in factory_girl

The :with_price trait needs to be on a separate line from the other attributes you're setting, i.e. use this:

trait :with_usd_price do
with_price
short_name: 'USD'
end

instead of this:

trait :with_usd_price do
with_price short_name: 'USD'
end


Related Topics



Leave a reply



Submit