Forum: Ruby on Rails Unit Tests and Default Values

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9ae68be4f6aff5c6aa7a0eb7087251e9?d=identicon&s=25 PeteSalty (Guest)
on 2007-05-16 22:51
(Received via mailing list)
We have a fairly simple model that appears to be throwing an error
when using unit tests, but we don't know why. Seems to work well
enough from our controllers just throws the error in test.
We have a table that contains a field called user_id that holds the ID
of the user who created the post. The definition is:

t.column "user_id",  :integer, :null => false

The post model belongs to :user and user has_many :posts

This works fine except for unit tests, for some bizzare reason. When
we perform a simple unit test like

  def test_blank_post

    post = Post.create(:user  => users(:spanogebob))
    assert !post.valid?

  end

which should assert to true since the body of the post will be blank,
which is not allowed. However, what we get is a MySQL error:

Field 'user_id' doesn't have a default value: Insert into
'posts' ('id') values (2)

Anyone have any idea why this is happening.

Thanks in advance
Dale
83ca41657a99b65d99889abe712ba5e2?d=identicon&s=25 Jason Roelofs (Guest)
on 2007-05-16 22:57
(Received via mailing list)
Does

post = Post.create(:user_id => users(:spanogebob).id)

work for you?

Jason
9ae68be4f6aff5c6aa7a0eb7087251e9?d=identicon&s=25 PeteSalty (Guest)
on 2007-05-17 02:09
(Received via mailing list)
No, unfortunately it's the same if we do that.

Dale
9ae68be4f6aff5c6aa7a0eb7087251e9?d=identicon&s=25 PeteSalty (Guest)
on 2007-05-18 01:31
(Received via mailing list)
Wow, I've been on this for days now and can't seem to work out where
I'm going wrong.
It must be something I'm doing wrong
83ca41657a99b65d99889abe712ba5e2?d=identicon&s=25 Jason Roelofs (Guest)
on 2007-05-18 15:16
(Received via mailing list)
Hmm. I guess you could write some tests proving that the has_many /
belongs_to relationships exist and are working. Otherwise we'll need to
see
code to help you out.

Jason
Ba3a00606eb530dcab2c4a6a59bf366d?d=identicon&s=25 Alain Ravet (Guest)
on 2007-05-18 16:24
(Received via mailing list)
Pete,

  >     post = Post.create(:user  => users(:spanogebob))
  > we get is a MySQL error:

What happens where you don't use fixtures but real objects :

  #  fixtures ....  don't load any fixture at all
  #
  spongebox = User.create( ...)
  post = Post.create(:user  => spanogebob)


Alain Ravet
--------
http://blog.ravet.com
This topic is locked and can not be replied to.