Stubbing Grape Helpers

At rainforest we use rspec for testing. Our API layer is using Grape. Both projects have their ups and downs.

I’m still pretty new to ruby and the tooling you have in Ruby. Today I was stuck for a couple of hours because I wanted to stub an endpoint helper. I’m writing this down here for my own sanity and also, in case anybody else is looking for a solution to the same problem. So here you go:

describe MyAPI do
  context 'with a logged in user' do
    before do
      Grape::Endpoint.before_each do |endpoint|
        endpoint.stub(:current_user).and_return mock(:User, name: "Bob Example")
      end
    end

What we’re doing here is we’re using the static before_each method of Grape::Endpoint to stub out the :current_user helper that belongs to the scope of this endpoint.

This will affect every Endpoint that gets instantiated from here on out, so next we need to clean up after the lifecycle of this describe block has ended with rspecs after method:

    after { Grape::Endpoint.before_each nil }

Once that’s done you can safely assume that inside this block, the helper will be stubbed:

    it "works" do
      get "/my/protected/endpoint"
      expect(response.status).to eq 200
    end
  end
end

Here is the code example in its entirety:

describe MyAPI do

  context 'with a logged in user' do
    before do
      Grape::Endpoint.before_each do |endpoint|
        endpoint.stub(:current_user).and_return mock(:User, name: "Bob Example")
      end
    end

    after { Grape::Endpoint.before_each nil }

    it "works" do
      get "/my/protected/endpoint"
      expect(response.status).to eq 200
    end
  end
end

And here’s the original source of this information. Thanks to my friend Jonathan at Rainforest who pointed me in the right direction!