Last active
August 14, 2018 15:42
-
-
Save jc00ke/5d05894deb9be28cb5d5f7b92303e343 to your computer and use it in GitHub Desktop.
Using Module prepend with an argument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/support/authenticated.rb | |
class Authenticated < Module | |
def initialize(current_user:) | |
super() do | |
define_method :current_user do | |
current_user | |
end | |
end | |
end | |
end | |
RSpec.shared_context "authenticated", shared_context: :metadata do | |
before do | |
described_class.prepend Authenticated.new(current_user: current_user) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/admin/controllers/study/create_spec.rb | |
RSpec.describe Admin::Controllers::Study::Create, type: :action do | |
let(:action) { described_class.new } | |
let(:params) { Hash[] } | |
let(:admin) { Fabricate.build(:admin) } | |
include_context "authenticated" do | |
let(:current_user) { admin } | |
end | |
it 'is successful' do | |
response = action.call(params) | |
expect(response[0]).to eq 302 | |
end | |
end |
Thanks to @epidemian and his suggestion to mock the described class:
# spec/support/authenticated.rb
RSpec.shared_context "authenticated", shared_context: :metadata do
before do
allow_any_instance_of(described_class).
to receive(:current_user).
and_return(current_user)
end
end
I find this to be much more straightforward and clear. I think I tried something akin to this but for some reason it didn't work. Not sure why. Anyway, this is very nice indeed!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://medium.com/@eric.programmer/arguments-for-included-modules-in-ruby-8056b9fa2743
Authentication in this application is done by magic link via email, and I didn't want to exercise that over and over again.
In a Hanami application, you can do something like
in
application.rb
which will set@current_user
in the actions.I found this
shared_context
+Authenticated
module to be a nice way tooverride
current_user
without messy hacks likeinstance_variable_set
.