Forum: Ruby on Rails How to test that a specific error message is thrown

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.
Jim B. (Guest)
on 2009-05-28 19:56
Hi,

If I have this line in my model:
validates_presence_of :name, :message => "Please enter a name"

and I test this with the following code:

def test_should_require_name
  user= User.new(valid_user_attributes(:name => ""))
  assert !applicant.save
end

Is there a way to write an additional test to ensure that not only the
name field may not be blank, but that if it is blank the message "Please
neter a name" is thrown?

Many thanks
Gavin M. (Guest)
on 2009-05-28 20:03
(Received via mailing list)
Yep

try...

def test_should_not_be_valid_without_name
  user = User.new
  user.valid?
  assert_equal user.errors.on(:name), "Please enter a name"
end
Jim B. (Guest)
on 2009-05-28 20:11
Hi,

That worked perfectly.
Thank you very much.
Gavin M. (Guest)
on 2009-05-28 20:19
(Received via mailing list)
You're welcome.

Just a little advice  -

It's generally better practice to be more specific with the names of
your tests.  I find it helps define exactly what it is you're testing
for.

Here's an article about BDD if you're interested:
http://dannorth.net/introducing-bdd
Jim B. (Guest)
on 2009-05-28 21:43
> Here's an article about BDD if you're interested:
> http://dannorth.net/introducing-bdd

Hey, cool article. Thanks a lot.
I will read that through this evening.
I'm still a bit new to TDD and am still finding my way around, so thanks
for the advice.
Gavin M. (Guest)
on 2009-05-28 22:10
(Received via mailing list)
I'd also recommend checking out rspec.

It's a BDD framework that helps you write tests that feel a lot more
intuitive than the default rails testing suite.

simply install the rspec gem and the rspec-rails gem

Specs are written like:

describe User do

  it "should not be valid without a name" do
    user = User.new
    user.valid?
    user.errors.on(:name).should == "can't be blank"
  end

end

Hope you find that useful
:)
Jim B. (Guest)
on 2009-05-29 00:09
> Hope you find that useful
> :)

Thanks for the tip.
I'm currently reading a book "Professional Webdevelopment with RoR2" by
Jens-Christian F. and he's just getting into Rspec.
I wasn't sure how indepth I should read that part, but now I will
definitely take the time to check it out.
This topic is locked and can not be replied to.