Reputation: 2131
I have a helper module with a method that fires off redirect_to
if the current user does not have permission to visit a web page.
I am getting a NoMethodError
error when running the tests, since the helper does not actually have a redirect_to method. I have tried stubbing out redirect_to like this:
it "redirects the user to the user's langing page if the user doesn't have permission" do
allow(helper).to receive(:current_or_guest_user) { test_user }
expect(helper).to receive(:redirect_to)
helper.require_permission :view_admins
end
but I get a long long error that the helper does not implement redirect_to
.
Is there a way to stub out this method?
Upvotes: 3
Views: 671
Reputation: 1223
You could create an anonymous
controller in your spec and include your module in it. When you've got that, you can test it like a normal controller action/method. So, add something along the lines of this to your spec:
controller(YourController) do
include YourModule
def index
render text: 'body'
end
end
I don't know whether your method is a before_action
or not, but it seems like it is since you're testing whether the user has the required view_admins
permission.
So, when the user has the required permission, your spec should be something like this:
context 'when the user has the required permission' do
before do
# make sure the user has the required permission
end
it 'the user will see the rendered text' do
get :index
expect(response.body).to eq 'body'
end
end
And when the user doesn't have the required permission they'll be redirected to the path you've defined. So, something like this:
context 'when the user does NOT have the required permission' do
before do
# make sure the user does NOT have the required permission
end
it 'the user will be redirected to the specified path' do
get :index
expect(controller).to redirect_to your_specified_path
end
end
More information about anonymous
controllers can be found here.
Upvotes: 2