raycons
raycons

Reputation: 835

IntegrationTest with Mocha, stub HelperMethod (Ruby)

I got a helper method:

has_permission?

In a Module called:

module ApplicationHelper

Inside app/helpers.

I also have an IntegrationTest which includes it:

include ApplicationHelper

My Integration test calls one of my controllers via get request.

On call I want to test if my integration test arrives at a certain method.

On this way is has to pass a few of the methods, one of those being the

has_permission?

In order to make sure this method passes I wanted to stub it.

Object.any_instance.expects(:has_permission?).returns(false) Doesn't work

ApplicationHelper.expects(:has_permission?).returns(false) Doesn't work either because it's not a static method.

Is there a way I can stub the helpers non-static method within the test so I can make it return false in all cases?

The test:

test "test try to edit without permission" do
@curr = users(:me)
sign_in @curr

SellingController.expects(:validate).never

post enable_update_user_selling_path(id: @user, params: {user: {sell: "1"}})

end

Upvotes: 5

Views: 719

Answers (2)

raycons
raycons

Reputation: 835

Forgot to post how I ended up solving this:

SellingController.any_instance.stubs(:has_permission?).returns(false)

Upvotes: 0

Leo
Leo

Reputation: 1629

Stumbled across this when trying to work out how to stub an ApplicationHelper method in an ActionDispatch::IntegrationTest in Rails 5; not sure if that's exactly what you're trying to achieve but I ended up doing something like this

MyController.view_context_class.any_instance.expects(:my_method).returns(true)

It looks as though since Rails 5, helper methods aren't simply mixed into the controller classes directly hence the view_context_class bit.

Seems to work, hopefully this will be helpful to someone!

Upvotes: 3

Related Questions