2016-03-15 78 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是我的一個根本問題,現在我至少知道該怎麼解決:)儘管我的問題與測試無關,只是不時發生的通常會發生的錯誤好。 –