Testing ViewComponents with Devise #371
Replies: 2 comments 2 replies
-
@jordanbrock thanks for taking the time to file this issue! Compatibility with common frameworks like Devise is important. I see a couple possible paths to take here: 1) Pass in the user!If you were to pass 2) Create your own test helperThis is what we do in the GitHub codebase: module GitHub
module ComponentTestHelpers
include ViewComponent::TestHelpers
def as(user)
controller.send(:current_user=, user)
end
end
end Which allows us to write tests like: as(@user)
render_inline(Dashboard::BannerComponent.new) 3) Update ViewComponent to be compatible with Devise!It'd be pretty cool to see us support the use case you describe out of the box. We already have some test helpers included with the library: https://github.com/github/view_component/blob/master/lib/view_component/test_helpers.rb, perhaps we could make changes that would support Devise? |
Beta Was this translation helpful? Give feedback.
-
22024-08 I'm using this to access Devise
note bonus you are able to modify controller params like this:
|
Beta Was this translation helpful? Give feedback.
-
Howdy all,
TL;DR:
Unable to test a view component that relies on a devise helper method
Just starting out on converting an existing site to use ViewComponents, and I've run into a little snag. The site has a news feed, that is essentially an array of a number of different objects (new products, new customers, comments etc).
I have a ViewComponent that uses :with_collection_parameter that iterates the items, and determines which partial to render, based on the object type.
The component view file then renders that partial
It's working fine in development, but when I try and write a test to make sure the correct partials are being rendered I'm getting an error. The partial makes a call to "current_user" which is a method provided by Devise. Normally in Controller tests, you can include Devise::TestHelpers and it will inject appropriate code into the @request.env to help the test run.
However, when I put the following in my test_helper.rb
I get the following error:
which is devise attempting to do the following:
Does anyone have any suggestion on how to get the tests to run?
Beta Was this translation helpful? Give feedback.
All reactions