I am just starting to use unit testing. Way cool. But I am not finding very clear docs on assert_raise. I have managed to write a test that tells me that the destroy I am trying to test fails with a RuntimeError (as it should). However, I would really like to test that it rails for the specific reason I have in my model. How can I get more specific? Am I going to have to create my own exception class so I have a named exception to check for? What I have a the moment is: In my model file: # don''t destroy the home page (id = 1) before_destroy :dont_destroy_homepage def dont_destroy_homepage raise "You can''t delete the home page or you will get rid of your entire site" if id == 1 end Then in my test file: def test_cant_destroy_homepage homepage = pages(:homepage) assert_equal homepage.id, 1 # I would really love to figure out how to test what RuntimeError is raised assert_raise(RuntimeError) {homepage.destroy} end -- Cynthia Kiser
exception = assert_raise(RuntimeError) {homepage.destroy} puts exception.message (I think) Chris On 7/18/06, Cynthia Kiser <cynthia.kiser@gmail.com> wrote:> I am just starting to use unit testing. Way cool. But I am not finding > very clear docs on assert_raise. I have managed to write a test that > tells me that the destroy I am trying to test fails with a > RuntimeError (as it should). However, I would really like to test that > it rails for the specific reason I have in my model. How can I get > more specific? Am I going to have to create my own exception class so > I have a named exception to check for? What I have a the moment is: > > In my model file: > > # don''t destroy the home page (id = 1) > before_destroy :dont_destroy_homepage > > def dont_destroy_homepage > raise "You can''t delete the home page or you will get rid of your > entire site" if id == 1 > end > > Then in my test file: > > def test_cant_destroy_homepage > homepage = pages(:homepage) > assert_equal homepage.id, 1 > # I would really love to figure out how to test what RuntimeError is raised > assert_raise(RuntimeError) {homepage.destroy} > end > > > -- > Cynthia Kiser > _______________________________________________ > Rails mailing list > Rails@lists.rubyonrails.org > http://lists.rubyonrails.org/mailman/listinfo/rails >
On 7/18/06, Chris Roos <chrisjroos@gmail.com> wrote:> exception = assert_raise(RuntimeError) {homepage.destroy} > puts exception.messageThanks Chris. That does indeed print the message to the console - and told me how to access the message. I altered my test to then assert the message was what I wanted: def test_cant_destroy_homepage homepage = pages(:homepage) assert_equal homepage.id, 1 problem = assert_raise(RuntimeError) {homepage.destroy} assert_equal "You can''t delete the home page", problem.message end And I was please to note that the assert_raise still counted in my number of assertions. -- Cynthia Kiser cynthia.kiser@gmail.com