0

I'm working on functionality testing on a Rails website that uses Devise, and I've run into a strange problem. I needed to figure out how to simulate a login, and after a little searching, I found this question that told me about Devise::TestHelpers and the sign_in function. Oddly enough, though, it's working in some but not all of my tests. Here's a couple of my tests:

include Devise::TestHelpers

setup do
  @game = games(:game_one)
  @user = users(:one)
  sign_in(@user)
end

# This test passes
test "should get index" do
  get :index
  assert_response :success
  assert_not_nil assigns(:games)
end

# This test fails; the post redirects to /users/sign_in
# as if accessed without logging in
test "should create game" do
  assert_difference('Game.count') do
    post :create, game: { name: @game.name }
  end

  assert_redirected_to game_path(assigns(:game))
end

And the controller itself looks like this:

class GamesController < ApplicationController
  before_filter :authenticate_user!

  # Some mostly-autogenerated CRUD
end

From what I can tell, the main difference between the tests that are working and the tests that think I haven't logged in is that the former are using get and the latter post. Is that something that makes sense? And how can I fix it?

Edit: Is this something to do with the "scope" that the Devise readme mentions? It doesn't really explain what that means, but it seems like it may be relevant.

Community
  • 1
  • 1
user1618143
  • 1,728
  • 1
  • 13
  • 27
  • 1
    I would check your logs. Make sure it's not complaining about the authenticity token, or something else fishy with the request. – Farley Knight Sep 08 '13 at 14:11
  • @farleyknight: Good call. It's not getting valid CSRF tokens, which apparently is okay for GET requests but not any other type. – user1618143 Sep 09 '13 at 14:23

1 Answers1

0

Aha! Thanks to farleyknight's comment, I discovered it was complaining about CSRF token authenticity. From there, this question had a working solution. I added this to my ApplicationController:

skip_before_filter :verify_authenticity_token if Rails.env.test?

There's probably a way to actually send valid CSRF tokens as part of the test, which would probably be a better solution, but this one's working for me.

Community
  • 1
  • 1
user1618143
  • 1,728
  • 1
  • 13
  • 27
  • You could add this to your `config/environments/test.rb` file: `config.action_controller.allow_forgery_protection = false` – Chloe Jun 17 '14 at 23:01