Andrew K Kirk
Andrew K Kirk

Reputation: 301

Error between validate method in Model and Test:Unit assertion results

Ruby Noob - I've searched SO, read the Rails Guide on Testing, and watched a RailsCast without luck.

I'm unable to reconcile method associations with tests I've written. Currently (code below), both tests, one checking for presence of name and one checking for presence of email, pass without failure or error -- ok, seems good.

If I remove both validates statements from the model, both tests fail -- also, makes sense.

However, if I remove only ONE of either

validates :name, :presence => true

OR

validates :email, :presence => true

from the model, BOTH tests pass without failure. This result does not make sense to me. Have I created faulty tests?


user.rb model:

class User < ActiveRecord::Base
  attr_accessible :email, :name 

  has_many :connections

  validates :name, :presence => true
  validates :email, :presence => true
end

test/unit/user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test "a user should have a name" do
    user = User.new
    assert !user.save
  end

  test "a user should have an email" do
    user = User.new
    assert !user.save
  end
end

Upvotes: 2

Views: 406

Answers (1)

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

Yes, you have created faulty tests. In any test, you need to test only a single premise, as in a user should have name should just the user validate presence of name.

First lets take why both tests pass in your third case, as in only one of the validates statements is present in the model.

Your test code,

   user = User.new
   assert !user.save

So if you have either validates :name, :presence => true or validates :email, :presence => true

user.save will return false, user object will not save because whichever validation is present would take effect.

You may want to change the tests to check error on the name.

 user = User.new
 assert !user.save
 assert  !user.errors.get(:email).blank?
 user = User.new
 assert !user.save
 assert  !user.errors.get(:name).blank?

You may also want to take a look at https://github.com/thoughtbot/shoulda , helps make writing tests easier :)

Upvotes: 1

Related Questions