ruby-on-railsunit-testingauthenticity-token

Testing controller methods protected from forgery in Rails


I'm trying to test a method I have in my application, but I don't know how to unit test a method that is being protected from forgery, take a look at this:

    def index
    @alumnos = Alumno.paginate :per_page => 20, 
      :page => params[:page], :order => :nombre

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @alumnos }
    end
  end

In the index.html.erb I have this line:

<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>

So, when I try to test it with a functional test, it seems that the session doesn't have the secret work which will cause the test to fail, does anyone have experience testing this methods?


Solution

  • Here is one solution (or a workaround) : in your controllers/application.rb

       if RAILS_ENV =='test'
        protect_from_forgery  :secret => 'write ur secret in config/environment.rb'
    
      else
    
    protect\_from_forgery
    
      end