2016-03-15 77 views
6

我正在使用宝石punditdevise。我有一个删除链接,只有当您是管理员时才会显示。我有一个集成测试,我想验证删除链接只显示管理员。Ruby on Rails Pundit的current_user在集成测试中为零

test 'comment delete link shows when it should' do 
    log_in_as @admin 
    get movie_path(@movie) 
    assert_select 'a[href=?]', movie_comment_path(comments(:one), @movie.id) 
end 

test_helper.rb看起来是这样的:

... 
class ActiveSupport::TestCase 
    ... 
    def log_in_as(user, options = {}) 
    password = options[:password] || 'password' 
    if integration_test? 
     post user_session_path, 'user[email]' => user.email, 'user[password]' => user.password 
    else 
     Devise::TestHelpers.sign_in user 
    end 
    end 

    private 

    # Returns true inside an integration test. 
    def integration_test? 
     defined?(post_via_redirect) 
    end 

end 

response.body看上去一切正常,但确确实实没有删除链接。有一个我运行开发服务器并自己访问该页面。我将这个范围缩小到了current_user,那些权威人士在政策中使用的值为nil。这是我的comment_policy.rb

class CommentPolicy 
    attr_reader :current_user, :comment 

    def initialize(current_user, model) 
    @current_user = current_user 
    @comment  = model 
    end 

    def create? 
    if @current_user 
     @current_user.member? or @current_user.content_creator? or @current_user.moderator? or @current_user.admin? 
    end 
    end 

    def destroy? 
    if @current_user 
     @current_user == @comment.user or @current_user.moderator? or @current_user.admin? 
    end 
    end 

end 

由于关闭的话,我听说Rails的5选择了集成测试,而不是控制器的测试,因为我们知道他们从测试的默认类型的Rails 4的生成我们的控制器如果是这样的话,devise如果在控制器测试中工作的sign_in/sign_out助手也可以在集成测试中工作,那么在使用Rails 5时可能会更加有用。但是,我仍然有这个问题pundit不知道current_user是什么?我假设这一切都在控制器测试中正常工作,因为current_user被限制在控制器?任何和所有关于这个话题的灯光都非常感谢,但我真的很想弄清楚如何使用这个设置来进行集成测试,因为我现在有大约10亿的数据需要编写。

回答

1

不是完全重要,而是需要在策略中使用current_user还是只能在策略中使用用户。我的意思是根据Github上的elabs/pundit README,我只是使用@useruser而不是current_user。如果我困惑你,请阅读自述文件。

此外nil对于current_user通常会发生在您的请求没有有效的CSRF令牌时。当您在网站上通过localhost:3000或w/e手动执行此操作时,首先在登录路径上执行get,然后在登录路径上使用您的凭据进行发布。在你的集成测试中,我似乎没有看到你在哪里执行get以获得会话的CSRF。

希望这有助于!

+0

非常感谢你,CSRF是我的一个根本问题,现在我至少知道该怎么解决:)尽管我的问题与测试无关,只是不时发生的通常会发生的错误好。 –