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