Alain ANDRE
Alain ANDRE

Reputation: 305

Testing Grape api. ActionController::TestCase @controller is nil

I'm trying to test my grape api and I'm having problems with my test.

I use the rails default test, this is my Gemfile test part.

group :development, :test do
  gem 'sqlite3'  
  gem 'byebug' # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'spring' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'factory_girl_rails'
  gem 'capybara'
  gem 'selenium-webdriver'
  gem 'capybara-angular'
  gem 'poltergeist'
  gem 'phantomjs', :require => 'phantomjs/poltergeist', platforms: :ruby # linux
end

My controller :

# app/controllers/api/v1/vehicules.rb
module API
  module V1
    class Vehicules < Grape::API

and my test :

# test/controllers/api/v1/vehicules_test.rb
require "test_helper"

class API::V1::VehiculesTest < ActionController::TestCase
  @controller = API::V1::VehiculesTest.new

  test "GET /api/v1/vehicules?user_id=123" do
    get("/api/v1/vehicules?user_id=123")
    assert_response :success
    json_response = JSON.parse(response.body)
    assert_not(json_response['principal'], "principal devrait être faux")
  end

  test "PUT /api/v1/vehicules?user_id=123" do
    put("/api/v1/vehicules?user_id=123", { 'princiapl' => true }, :format => "json")
    assert_response :success
    json_response = JSON.parse(response.body)
    assert_not(json_response['principal'], "principal devrait être vrais")
  end

end

When I launch the test, I got this error :

  1) Error:
API::V1::VehiculesTest#test_GET_/api/v1/vehicules?user_id=123:
RuntimeError: @controller is nil: make sure you set it in your test's setup meth
od.
    test/controllers/api/v1/vehicules_test.rb:7:in `block in <class:VehiculesTes
t>'

I couldn't find why the controller is not found. Do I have to add something in my test_helper.rb ? It contains nothing for ActionController :

class ActionController::TestCase

end

Upvotes: 1

Views: 742

Answers (1)

Kieran Johnson
Kieran Johnson

Reputation: 1353

You're setting up your test as a normal Rails controller test but its slightly different for a Grape class.

Instead of inheriting from ActionController::TestCase you should just inherit from ActiveSupport::TestCase, then include the Rack test helpers.

e.g.

class API::V1::VehiclesTest < ActiveSupport::TestCase
  include Rack::Test::Methods

  def app
    Rails.application
  end

  test "GET /api/v1/vehicules?user_id=123" do
    get("/api/v1/vehicules?user_id=123")

    assert last_response.ok?

    assert_not(JSON.parse(last_response.body)['principal'], "principal devrait être faux")
  end

  # your tests
end

See https://github.com/ruby-grape/grape#minitest-1 and https://github.com/brynary/rack-test for further details.

Upvotes: 2

Related Questions