title: Using rspec to test an API endpoint
body: <p>I have this api endpoint wot get all the blogs from my database that works id the user pass an api_key. This works correctly and now I'm trying to testing this endpoint.</p>
  <p>Routes:</p>
  <pre><code>Rails.application.routes.draw do
    get 'blogs', to: 'blogs#index'
  end
  </code></pre>
  <p>Blogs controller:</p>
  <pre><code>class BlogsController &lt; ApplicationController
    def index
      if params[:api_key]
        user = User.find_by(api_key: params[:api_key])
        if user.present?
          @blogs = Blog.all
          return render json: @blogs, status: :ok   
        end         
      end
      render json: { error: &quot;Unauthorized!&quot; }, status: :bad_request
    end
  end
  </code></pre>
  <p>I'm new to rspec and tests in general, I watched a couple videos and tutorials and this is what I have so far:</p>
  <p><code>spec/requests/blogs_spec.rb</code></p>
  <pre><code>require 'rails_helper'
  
  RSpec.describe 'Blogs API', type: :request do
    let!(:blogs) { Blog.limit(10) }
  
    describe 'GET /blogs' do
      before { get '/blogs' }
      
      it 'returns status code 400' do
        expect(response).to have_http_status(400)
      end
  
      context 'when the request is valid' do
        before { get '/blogs', params: { api_key: '123123'} }
  
        it 'returns status code 400' do
          expect(response).to have_http_status(200)
        end
      end
    end
  end
  </code></pre>
  <p>I can't seem to make the last test work and I don't know why. My guess is that I'm not passing <code>api_key</code> correctly, but I don't know how</p>
  <pre><code> 1) Blogs API GET /blogs when the request is valid returns status code 400
       Failure/Error: expect(response).to have_http_status(200)
         expected the response to have status code 200 but it was 400
       # ./spec/requests/blogs_spec.rb:28:in `block (4 levels) in &lt;top (required)&gt;'
  </code></pre>