测试葡萄api。 ActionController :: TestCase @controller是零

时间:2016-04-07 13:11:30

标签: ruby-on-rails testing grape

我试图测试我的grape api并且我的测试有问题。

我使用rails默认测试,这是我的Gemfile测试部分。

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

我的控制器:

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

和我的测试:

# 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

当我启动测试时,我收到了这个错误:

  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>'

我无法找到找不到controller的原因。我是否必须在test_helper.rb中添加内容?它不包含ActionController

的任何内容
class ActionController::TestCase

end

1 个答案:

答案 0 :(得分:2)

您将测试设置为普通的Rails控制器测试,但对于Grape类略有不同。

您应该继承ActionController::TestCase,而不是继承自ActiveSupport::TestCase,而是包含Rack测试助手。

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

有关详细信息,请参阅https://github.com/ruby-grape/grape#minitest-1https://github.com/brynary/rack-test