Rspec unit test fails sometimes (validation race condition)

I have code similar to this:

class Post
has_many :comments
end

class Comment
belongs_to :post
validate :must_not_exceed_ten

def must_not_exceed_ten
errors.add_to_base(‘Too many comments’) unless post.comments.length
< 10
end
end

and in the specs (Rspec + machinist):

post = Post.make
9.times { Comment.make(:post => post) }
comment = Comment.new(:post => post)
comment.save.should be_false

The weird thing about it is that it fails sometimes! Especially if I run
the whole test suite with rake command (the probability is higher). When
I check in the console post indeed has 11 comments. Can somebody give me
a reasonable explanation why this is happening? Is this some sort of a
race condition that I’m missing?

In the specs it is actually 10.times instead of 9.

Milan D. wrote:

post = Post.make
9.times { Comment.make(:post => post) }
comment = Comment.new(:post => post)
comment.save.should be_false

Milan D. wrote:

In the specs it is actually 10.times instead of 9.

Milan D. wrote:

post = Post.make
9.times { Comment.make(:post => post) }
comment = Comment.new(:post => post)
comment.save.should be_false

Well, there’s your problem, then – you’ve already made your 10th
comment!

BTW, you should consider comments.count instead of .length – let the DB
do the counting.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

No because validations happen before the object is saved. Validation
will pass and the object will get saved properly. Well… sometimes.
Sometimes not.

Marnen Laibow-Koser wrote:

Well, there’s your problem, then – you’ve already made your 10th
comment!

BTW, you should consider comments.count instead of .length – let the DB
do the counting.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]