Danny
Danny

Reputation: 4754

Factory Girl not destroying objects properly

I am creating an object with several has_many associations. Everything with regards tob building the object works fine, but when I try to test the deletion of one of the children or parent, it does not reflect in the test.

For example:

 base_article = Factory(:base_article, :articles => [Factory(:article)])
 p base_article.articles.size
 base_article.articles.first.destroy
 p base_article.articles.size
 base_article.destroyed?.should == true

This prints out:

1

1

I am testing the callback after destroy on the article that deletes the base when there are no more children. Why is the size of the articles association not being reduced by one?

Thanks!

Upvotes: 1

Views: 2028

Answers (2)

Damon Black
Damon Black

Reputation: 1

You could used articles.count instead. 'Size' gives you the length of the in-memory collection. Count does a query and gets the latest total from the db.

Upvotes: 0

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

You need to reload the articles collection as Rails' database caching is stale:

base_article = Factory(:base_article, :articles => [Factory(:article)])
base_article.articles.size # => 1

base_article.articles.first.destroy
base_article.articles.size # => 1
base_article.articles.reload.size # => 0

base_article.destroyed?.should == true 

Upvotes: 6

Related Questions