Following are models:
class User < ActiveRecord::Base
has_many :companies_users
has_many :companies, :through => :companies_users
end
class Company < ActiveRecord::Base
has_many :companies_users
has_many :users, :through => :companies_users
accepts_nested_attributes_for :users
attr_accessible :name, :address_1, :address_2, :area, :city, :state, :zipcode, :country, :users_attributes
after_create :create_subscriptions
def create_subscriptions
subscription=Subscription.create(:company_id => self.id, :subscription_dt => Date.today, :is_active => 'Y', :user_id => self.users.first.id)
subscription.save
end
end
class CompaniesUser < ActiveRecord::Base
belongs_to :user
belongs_to :company
end
Following are spec/factories/factory.rb
FactoryGirl.define do
factory :company do |f|
f.name "TestCompany"
f.domain_url "test_url"
users {|t| [t.association(:user)] }
end
factory :user do |f|
f.first_name "John"
f.last_name "Doe"
f.password "password"
f.email "JohnDoe@test.com"
f.mobile_no "25589875"
f.fax_no "25548789"
f.office_no "25578455"
end
factory :companiesuser do |f|
association :user
association :company
end
end
Following is my spec/model/company_spec.rb
context "Check methods" do
it "check after create methods" do
company = FactoryGirl.create(:company)
end
end
While executing above company_spec it creates an issue due to method subscription which exist in company model and call after create callback create_subscriptions.which require self.users.first.id which it did not get and provide me following error.
$ rspec spec/models/company_spec.rb
F
Failures:
1) Company Model: Check methods check after create methods
Failure/Error: company = FactoryGirl.create(:company)
RuntimeError:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
# ./app/models/company.rb:47:in `create_subscriptions'
# ./spec/models/company_spec.rb:45:in `block (3 levels) in <top (required)>'
Can anyone let me know what i need to do or its any association related issue? it create problem because first it enter values in company but not able to enter value in users table so not get user id which required in subscription method.