Antony Sastre
Antony Sastre

Reputation: 617

RSpec testing relationship logic

I'm testing the following:

Account

class Account < ActiveRecord::Base 
  has_many :ownerships
  has_many :brands, :through => :ownerships
end

Ownership join model

class Ownership < ActiveRecord::Base
  belongs_to :brand
  belongs_to :account
end

Test

it "should be able to apply for brand ownership" do
  account = Account.create(valid_account_attributes)
  account.ownerships.create(:brand => Brand.create(:name => 'Superuser'))
  account.ownerships.first.state == 'pending'
end

And I keep getting this error

You cannot call create unless the parent is saved

I really don't get it - what parent? Shouldn't all the models be created and saved when using 'create'-method? I've tried putting 'account.save' everywhere.

Upvotes: 4

Views: 2576

Answers (2)

Andr&#233;
Andr&#233;

Reputation: 1

I had the same error. I thought I had deleted all rows of my tables but still had one with a user, the same user I was trying to insert with the command. I solved the problem by erasing the line.

Upvotes: 0

zetetic
zetetic

Reputation: 47578

Are you sure that account is actually saved? Did you try using create! to see if any exceptions are raised?

Upvotes: 1

Related Questions