ruby on rails - How to use factorygirl to associate user_id -


i learning tests using rails testing tools, mainly: rspec, factory_girl, shoulda, , faker gems.

i want test has_one , belongs_to associations. have user.rb (with name) , address.rb (with street, city, , user_id) models.

i trying figure out how create fake associations using fakers. want create fake street , associate fake user, can't figure out how on spec/factories/addresses.rb

this have:

factorygirl.define   factory :address     street    {faker::address.street_address}     city      {faker::address.city}     #creates fake user , use user's id user_id)#     user = build(:user, name: "joe", id: 2)     user_id   {user.id}   end end 

this spec/models/address_spec.rb

require 'rails_helper'  rspec.describe address, type: :model   "has valid factory"     address = build(:address)     expect(address).to be_valid   end   {should belong_to(:user)} end 

when run it, shows add_attribute': wrong number of arguments (given 3, expected 1..2) (argumenterror) error. tried removing id on argument , did user = build(:user, name: "joe") same error message still shows.

the test passes if don't include user lines on addresses factory. confirmed address has belongs_to :user , user has has_one :address.

is possible generate fake association , associate address fake user.id? test address's user_id well.

edit - following related factories , models:

factories

addresses.rb

factorygirl.define   factory :address     street    {faker::address.street_address}     city      {faker::address.city}     user   end end 

users.rb

factorygirl.define   factory :user     name      {faker::name.name}   end end 

spec/models

address_spec.rb

require 'rails_helper'  rspec.describe address, type: :model   "has valid factory"     association user     specific_user = build(:user, name: 'joe')     address = build(:address, specific_user)     expect(address).to be_valid   end   {should belong_to(:user)} end 

error running address_spec.rb

 nameerror:    undefined local variable or method `user' #<rspec::examplegroups::address:0x00000001a94b00>  # ./spec/models/addres 

i think way build association incorrect. see https://github.com/thoughtbot/factory_girl/blob/master/getting_started.md#associations.

if want more specific associated user eg name: joe, id: 2, it's better in spec.

factory:

factorygirl.define   factory :address     street    {faker::address.street_address}     city      {faker::address.city}     user   end end 

spec:

 "has valid factory"     specific_user = build(:user, name: 'joe')     address = build(:address, specific_user)     expect(address).to be_valid  end 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -