Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
MexicanHacker Avatar asked Jun 30 '26 05:06

MexicanHacker


1 Answers

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
like image 198
Alfreddd Avatar answered Jul 01 '26 23:07

Alfreddd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!