Rails根据环境调用具有不同格式的控制器方法

时间:2015-12-03 20:17:45

标签: ruby-on-rails json controller

我正在尝试确定为什么我的测试环境的行为与我的开发环境不同。如果我运行标准bundle exec rails s(因此在开发环境中)并通过Chrome localhost:3000/advertiser_types访问我的某条路线,则日志显示该请求将作为JSON处理:

Started GET "/advertiser_types" for 127.0.0.1 at 2015-12-03 14:08:18 -0600
Processing by AdvertiserTypesController#index as JSON
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 2  ORDER BY "users"."id" ASC LIMIT 1
  Advertiser Load (0.2ms)  SELECT  "advertisers".* FROM "advertisers"  WHERE "advertisers"."id" = $1 LIMIT 1  [["id", 1]]
Completed 200 OK in 9ms (Views: 3.1ms | ActiveRecord: 1.0ms)

如果我运行RAILS_ENV=test bundle exec rails s并尝试访问同一页面,请求将作为HTML处理,并抛出异常,因为我的控制器只返回JSON。

Started GET "/advertiser_types" for 127.0.0.1 at 2015-12-03 14:07:00 -0600
Processing by AdvertiserTypesController#index as HTML
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 3  ORDER BY "users"."id" ASC LIMIT 1
  Advertiser Load (0.3ms)  SELECT  "advertisers".* FROM "advertisers"  WHERE "advertisers"."id" = $1 LIMIT 1  [["id", 3]]
   (0.3ms)  SELECT COUNT(*) FROM "feeds"  WHERE "feeds"."advertiser_id" = $1  [["advertiser_id", 3]]
Completed 406 Not Acceptable in 4ms
Reporting exception: ActionController::UnknownFormat

控制器代码如下所示:

class AdvertiserTypesController < ApplicationController

  def index
    advertiser_types = AdvertiserType.all
    respond_to do |format|
      format.json { render json: advertiser_types}
    end
  end
end

为什么完全相同的请求会根据我所处的环境进行不同的处理?我无法弄清楚原因是什么。我的猜测是某处需要修改某种配置,但我不知道在哪里看。

1 个答案:

答案 0 :(得分:0)

我能够使用Capybara / Webkit重现此错误。显然,我的测试环境缺乏真实性令牌,以允许这些请求正常运行。在我的rspec配置中允许伪造保护允许我使用Webkit和Selenium来正常运行。