Search code examples
rubyruby-on-rails-5rspec-rails

How to send only 1 parameter with get method?


I have a controller with this index method (app/controllers/api/v1/users_controller.rb)

...
  before_action :find_user, only: [:show, :destroy]

  def index
    @users = User.order('created_at DESC')
  end
...

And I have a view (app/view/api/v1/users/index.json.jbuilder)

json.array! @users do |user|
  json.id user.id
  json.name user.name
  json.posts user.posts do |post|
    json.id post.id
    json.title post.title
    json.body post.body
  end
end

And when I run the server it works fine, after accessing localhost:3000/api/v1/users it is showing the expected output. But when I launch these RSpec tests (spec/controllers/api/v1/users_controller_spec.rb)

require 'rails_helper'

RSpec.describe Api::V1::UsersController, type: :controller do
  describe "GET #index" do
    before do
      get :index
    end
    it "returns http success" do
      expect(response).to have_http_status(:success)
    end
  end
end

I get an error enter image description here If I remove :index from get :index it gives the same error but (given 0, expected 1). How come get :index sending 2 parameters if there is only one and how can I rewrite this code so the test will pass?

If I rewrite index method like this

  def index
    @users = User.order('created_at DESC')
    render json: @users, status: 200 
  end

The test will pass, but in this case I will not get the JSON file that I need (which I made with jbuilder)


Solution

  • I found a solution some time ago. All I had to do is to place

      gem 'rspec-core', git: 'https://github.com/rspec/rspec-core'
      gem 'rspec-expectations', git: 'https://github.com/rspec/rspec-expectations'
      gem 'rspec-mocks', git: 'https://github.com/rspec/rspec-mocks'
      gem 'rspec-rails', git: 'https://github.com/rspec/rspec-rails'
      gem 'rspec-support', git: 'https://github.com/rspec/rspec-support'
      gem 'rails-controller-testing'
    

    in my Gemfile.