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.

4

1 回答 1

0

啊哈!感谢 farleyknight 的评论,我发现它在抱怨 CSRF 令牌的真实性。从那里,这个问题有了一个可行的解决方案。我将此添加到我的 ApplicationController 中:

skip_before_filter :verify_authenticity_token if Rails.env.test?

作为测试的一部分,可能有一种方法可以实际发送有效的 CSRF 令牌,这可能是一个更好的解决方案,但这对我有用。

于 2013-09-09T14:22:27.383 回答