0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[rspec] Grape APIのhelpersをスタブ化するメモ

Posted at

grape 1.3.3
rspec-rails 5.0.1

grape使っている際, current_userのようなよく使うものへスタブ差し込む方法が分からなかったのでメモ

諸々省略

app/apis/my_service/api.rb
class MyService::Api < Grape::API
  # 省略
  helpers do
    def current_user
      @current_user ||= User.find(params[:id])
    end
  end
end
spec/app/apis/my_service/v1/users_spec.rb
describe MyService::V1::Users do
  describe "GET /my_service/v1/user/:id" do
    subject { get "/my_service/v1/user/#{user.id}" }

    let(:user) { create(:user) }
    context "no good" do
      before do
        allow(User).to receive(:find).and_return(user)
      end
      it 'response user' do
        subject
        expect(my_response[:name]).to eq user.name
        ...
      end
    end
    context "good" do
      before do
        Grape::Endpoint.before_each do |endpoint|
          allow(endpoint).to receive(:current_user).and_return(user)
        end
      end
      after { Grape::Endpoint.before_each nil }

      it 'response user' do
        subject
        expect(my_response[:name]).to eq user.name
        ...
      end      
    end
  end
end

参考
https://github.com/ruby-grape/grape/issues/396

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?