views:

97

answers:

1

I have the following models:

class Activity < ActiveRecord::Base
  has_many  :clientships, :dependent => :destroy
  has_many  :clients, :through => :clientships
end

class Clientship < ActiveRecord::Base
  belongs_to  :client
  belongs_to  :activity

  validates_presence_of :client_id
  validates_presence_of :activity_id, :unless => :new_record?
end

class Client < ActiveRecord::Base
  has_many  :clientships
  has_many  :activities, :through => :clientships
end

I can't create an :activity factory as I get the validation error "Activity can't be blank".

My factories look like this:

Factory.define :activity do |a|
  a.association :staff, :factory => :user
  a.clientships { |cs| [cs.association :clientship] }
end

Factory.define :clientship do |cs|
  cs.association(:client)
end

Factory.define :client do |c|
  c.first_name {Factory.next(:name)}
  c.last_name {Factory.next(:name)}
end

I am getting the error when I run this factory in my spec: @activity = Factory(:activity)

PLEASE HELP!

+1  A: 

What I always do in cases like that is something like:

Factory.define :activity do |a|
  #whatever attributes
end

Factory.define :clientship do |cs|
  cs.association(:client)
  cs.association(:activity)
end

Factory.define :client do |c|
  c.first_name {Factory.next(:name)}
  c.last_name {Factory.next(:name)}
end

So in my tests/specs I use

Factory :clientship

Maybe it's not so clean, but makes much more sense to me... However I'm not sure that creating such a relationshipt from the join table is such a good idea.

And, in general I prefeer to create the associations in the factories from the belongs_to side since at the end it results being less problematic to me.

Francisco
Thanks for your answer. I also do something similar to the method you describe. The only issue in this case is the validation error within the Activity model...
Coderama
Yes, you use a similar way, but here `a.clientships { |cs| [cs.association :clientship] }` you create a clienthip with the default factory, which doesn't includes an activity. That's why you get the validation error. You need to create the activity before creating the clienship, you're doing it the other whay around.
Francisco
Ahh, I got confused. You're entirely right. Thank you!
Coderama
You're welcome!
Francisco