Rails - Using flash[:notice] Without Redirect
It has been a while since I last posted a blog on rails. I have been tied up with lots of stuff lately. And I just got my time back to move on with my first Rails project to build QuoteJetty. The ride has been fun, though many times I still have to google to find answers for issues that are not covered in Rails books.
One thing that I bumped into is the usage of flash[:notice].
I found out that flash[:notice] is meant only for redirect action, because the message is only cleared after at the end of redirected view request. So if you don’t redirect the request, and you click on the next request, that message will still be displayed.
But sometimes, we just want to display custom error messages only for current request without the redirection (esp. for non-ActiveRecord error messages). So the option is to use flash.now[:notice]. It clears the flash message at the end of current request (without redirection), e.g.
def some_method
.....
flash.now[:notice] = 'some message'
end
But there is an issue with functional testing using flash.now[:notice]. Since the message is cleared at the end of the request, you won’t be able to retrieve the flash[:notice] value in your functional test. But no worries, here is the alternative check, use assert_tag.
assert_tag compares the actual html output of your test in a convenient way, just like most of Ruby methods. Click here for the API doc.
def test_method
....
....
assert_tag :tag => 'div',
:child => /[replace with your message]/
end

Add Your Comment