I'm trying to test an action that needs a value stored in flash.
def my_action
if flash[:something].nil?
redirect_to root_path if flash[:something]
return
end
# Do some other stuff
end
In my test I do something like:
before(:each) do
flash[:something] = "bob"
end
it "should do whatever I had commented out above" do
get :my_action
# Assert something
end
The problem I'm running into is that flash has no values inside of my_action. I'm guessing this is because no request actually happens.
Is there a way to set flash up for a test like this?
The currently accepted way to test rails controllers is by sending http requests to your application and writing assertions about the response. Rails has ActionDispatch::IntegrationTest which provides integration tests for Minitest which is the Ruby standard library testing framework.
We can run all of our tests at once by using the bin/rails test command. Or we can run a single test file by passing the bin/rails test command the filename containing the test cases. This will run all test methods from the test case.
Most methods can be tested by saying, “When I pass in argument X, I expect return value Y.” This one isn't so straightforward though. This is more like “When the user sees output X and then enters value V, expect subsequent output O.” Instead of accepting arguments, this method gets its value from user input.
While unit tests make sure that individual parts of your application work, integration tests are used to test that different parts of your application work together.
I had to solve a simialr issue; I had a controller action that redirected to one of two paths at completion depending of the value of a hash entry. The spec test that I found worked, for your example above, was:
it "should do whatever I had commented out above" do
get :my_action, action_params_hash, @current_session, {:something=>true}
# Assert something
end
@current_session is a hash with session specific stuf; I'm using authlogic. I found about using the fourth argument of get for the flash in [A Guide to Testing Rails Applications[1]). I found that the same approach also works for delete; and I presume all others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With