0

RailsCast #350 REST APIのバージョニング#352 APIを保護してAPIを作成し、入力するとレストランのJSONインデックスを取得app/controllers/api/v1できるようにしました。localhost:3000/api/v1/restaurants

いくつかの機能テストを実行できるようにしたいと思います。私はこれを理解しようとしてきましたが、これを行う方法がわかりません。

これが私がこれまでにしたことです:

api_v1_restaurants_controller_test.rb私は自分のフォルダに作成し、次のtest/functionalようなことをしました:

require 'test_helper'
include Devise::TestHelpers

class ApiV1RestaurantsControllerTest < ActionController::TestCase
  fixtures :users, :roles, :restaurants, :menus, :ingredients, :dishes, :drinks

  setup do
    @restaurant = restaurants(:applebees)
    @user = users(:admin)
    @api = api_keys(:one)
  end

  test "should get restaurant index json data" do   
    assert_routing(
        'api/v1/restaurants',
        {:controller => 'api/v1/restaurants', :action => 'index', :format => 'json', :api_key => @api},
        {},
        {:api_key => @api}
    )
  end

テストは機能しているようですが、JSONを生成するshould get restaurant index json dataかどうかをテストできるようにしたいと思います。api/v1/restaurants/1?api_key=123456789

ここに私が書き込もうとしたこと:

test "should get restaurant id json data" do
  get 'api/v1/restaurants', :format => :json, :api_key => @api
  # get :get, :format => :json, :api_key => @api

  json = JSON.parse(@response.body)

  assert_equal Restaurant.first.id, json.first["id"]
end

しかし、実行後にコンソールで次のエラーが発生しますrake test:functionals

test_should_get_restaurant_id_json_data(ApiV1RestaurantsControllerTest):
RuntimeError: @controller is nil: make sure you set it in your test's setup method.

更新1:定義済み@controller

そのため、エラーメッセージを聞いて、@controller自分のsetup do...asで定義し@controller = Api::V1ましたが、コンソールに次のエラーメッセージが表示されます。

test_should_get_restaurant_id_json_data(ApiV1RestaurantsControllerTest):
NoMethodError: undefined method `response_body=' for Api::V1:Module
4

1 に答える 1

1

私はついにそれをすべて理解することができました。

あなたは@controllerこのようにあなたを定義する必要があります:

setup do
  ...
  @api = api_keys(:one)
  @restaurant = restaurants(:applebees)
  @controller = Api::V1::RestaurantsController.new
end

そして、JSONをテストするために次のようなテストを作成できるはずです。

test "json should be valid" do
  get :show, :format => :json, :api_key => @api.access_token, :id => @restaurant.id
  json = JSON.parse(@response.body)

  assert_equal @restaurant.id, json["id"]
  ...
end

生成されているJSONを確認する必要がある場合は、次のように記述できます(testブロック内)。

puts json # This will output the entire JSON to your console from JSON.parse(@response.body)

これが他の人にも役立つことを願っています。

于 2012-08-09T15:42:54.433 に答える