user2452057
user2452057

Reputation: 906

Rspec tests for multiple has_many, dependent destroy for a model

I have a model in rails which has mulitple has_many, :dependent => :destroy relationships in it.

class XYZ <ActiveRecord::Base
has_many :abc, :dependent => :destroy
has_many :def, :dependent => :destroy
has_many :ghi, :dependent => :destroy
.......
end 

I have rpec tests in xyz controller:

describe 'destroy' do
it 'should destroy all the entities in has_many' do
 @xyz= FactoryGirl.create(:xyz)
 @abc= FactoryGirl.create(:abc, :xyz=> @xyz)
 @def= FactoryGirl.create(:def, :xyz=> @xyz)
 @ghi= FactoryGirl.create(:ghi, :xyz=> @xyz)
 expect { @xyz.destroy }.to change { ABC.count }.by(-1)
end 
end 

How do I test whether destroying xyz actually decreases count of models Abc, Def and Ghi simultaneously? Or is the only way to do this is to write separate tests for individual has_many, dependent:destroy relationship?

Upvotes: 0

Views: 475

Answers (1)

ppascualv
ppascualv

Reputation: 1137

Use rspec-collection_matchers and use this piece of code, don't test already tested stuff.

it { should have_many(:abc).dependent(:destroy) }

Upvotes: 0

Related Questions