[Rails] Rspec unit test fails sometimes (validation race condition)

91 views
Skip to first unread message

Milan Dobrota

unread,
May 24, 2010, 6:50:51 PM5/24/10
to rubyonra...@googlegroups.com
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?
--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Milan Dobrota

unread,
May 24, 2010, 6:54:25 PM5/24/10
to rubyonra...@googlegroups.com
In the specs it is actually 10.times instead of 9.

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

Marnen Laibow-Koser

unread,
May 24, 2010, 7:08:09 PM5/24/10
to rubyonra...@googlegroups.com
Milan Dobrota wrote:
> In the specs it is actually 10.times instead of 9.
>
> Milan Dobrota 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
mar...@marnen.org

Milan Dobrota

unread,
May 24, 2010, 7:16:17 PM5/24/10
to rubyonra...@googlegroups.com
No because validations happen before the object is saved. Validation
will pass and the object will get saved properly. Well... sometimes.
Sometimes not.
Reply all
Reply to author
Forward
0 new messages