0

I followed the RailsCast #350 REST API Versioning and #352 Securing an API which creates an API under app/controllers/api/v1 so you can type in localhost:3000/api/v1/restaurants and you'll get the JSON for restaurants index.

I want to be able to do some functional testing. I've been trying to figure this out but am not sure how to do this.

Here's what I've done so far:

I created api_v1_restaurants_controller_test.rb in my test/functional folder and did something like this:

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

The should get restaurant index json data test seems to work but I want to be able to test to see whether api/v1/restaurants/1?api_key=123456789 generates JSON, which it should.

Here what I've tried to write up:

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

But I get the following error on my console after running 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.

Update 1: Defined @controller

So I listened to the error message and defined @controller under my setup do... as @controller = Api::V1 but now get the following error message on the console:

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 回答