是否可以在规范中使用'form_authenticity_token'?

时间:2014-04-15 02:50:58

标签: ruby-on-rails ruby ruby-on-rails-4 rspec devise

可以在Rails中的控制器中使用form_authencity_token

def create
  @user = self.resource = warden.authenticate!(auth_options)
  sign_in(resource_name, resource)
  @csrfToken = form_authenticity_token
  @user
end

我的问题是:是否可以在规范中包含form_authencity_value?我正在测试来自SessionsController设计)的控制器和JSON响应。我必须经常更新csrf-token,以免在我的请求中出现错误:无法验证CSRF令牌真实性

请,我已经向服务器发送了csrf-token,并且它已经完美运行了。我的问题在于 RSpec ,以便在登录后测试我的 RABL 响应(并注销 - 这不是 RABL 视图)。

我的测试是这样的:

expected_response = {
  'id'          => @user.id,
  'email'       => @user.email,
  'first_name'  => @user.first_name,
  'last_name'   => @user.last_name,
  'created_at'  => @user.created_at,
  'updated_at'  => @user.updated_at,
  'csrfToken'   => # PROBLEM
}.to_json

expect(response.body).to eq(expected_response)

如何在我的规范中包含form_authencity_value

2 个答案:

答案 0 :(得分:2)

如果您能够将其分配给@csrfToken,那么您需要的是:

{
   # ...
   @csrfToken' => assigns(:csrfToken)
}

assigns方法可以挖掘您设置的任何控制器实例变量。

答案 1 :(得分:0)

另一种可能性是如果你没有将form_authenticity_token分配给实例变量,则将其删除。

    expect(controller).to receive(:form_authenticity_token).and_return('a_known_value')

您可以使用expectallow。现在你有一个已知的值来比较。

相关问题