Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a value in flash when testing an action

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?

like image 976
Jared Avatar asked Oct 17 '11 11:10

Jared


People also ask

How to test controllers in rails?

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.

How to run test cases in rails?

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.

How do you test a method in Ruby?

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.

What is Rails integration test?

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.


1 Answers

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.

like image 195
jaambros Avatar answered Sep 29 '22 01:09

jaambros