Skip to content

Instantly share code, notes, and snippets.

@vmcilwain
Created October 31, 2019 13:14
Show Gist options
  • Save vmcilwain/12f6772de288b53adf6047b1261b0339 to your computer and use it in GitHub Desktop.
Save vmcilwain/12f6772de288b53adf6047b1261b0339 to your computer and use it in GitHub Desktop.
[minitest] Test view code that use pundit policies
module PostsHelper
def edit_link
link_to :Edit, edit_post_path(@post), class: 'btn btn-sm btn-dark' if policy(@post).update?
end
end
require 'test_helper'
class PostsHelperTest < ActionView::TestCase
test "should return edit link" do
@post = FactoryBot.create :post
self.current_user = @post.user
assert_dom_equal %{<a class="btn btn-sm btn-dark" href="/posts/#{@post.id}/edit">Edit</a>}, edit_link
end
end
# With the help of the following links, this setup worked for me:
# https://github.com/varvet/pundit/issues/301 (undefined method `policy' for ViewHelper)
# https://www.reddit.com/r/rails/comments/dp70gy/how_to_please_pundit_while_testing_view_helpers/
class ActiveSupport::TestCase
include Pundit
end
class ActionView::TestCase
# Used for assigning a user for pundit policies.
# to assign use `self.current_user` in the test
def current_user=(user=FactoryBot.create(:user))
@user = user
end
def current_user
@user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment