请求在Rails进行测试没有返回身体

问题描述:

我开始做一些测试,以我的应用程序中轨,并按照官方的教程中,我已经写了这一点:请求在Rails进行测试没有返回身体

class UserFlowTest < ActionDispatch::IntegrationTest 
    def login 
     post ns_login_user_path, { :user => { :username => 'user', :password => 'password' } } 
     assert_response 200 
    end 

    test "should complete a flow" do 
     login 
     post create_participant_path(:event_id => events(:myevent).id), { 
      :format  => :json, 
      :event_role => event_roles(:regular_participant).id, 
      :in_team => true 
     } 
     r = JSON.parse(response.body) 
     assert_response 200 
     puts "response creating participation #{r.as_json}" 
     participant_id = r[:participant_id] 
    end 
end 

它确实登录OK,但后当试图创建参与者时,response是一个没有.body属性的变量,只是数字200(状态),所以JSON.parse方法崩溃。

这是我routes.rb的相关部分:

# Events 
scope 'events', :controller => :events do 
    # some routes 
    scope ':event_id', :controller => :events do 
     # some routes 
     scope 'participants', :controller => :participants do 
      post '', :action => :create_participant, :as => :create_participant 
      # some routes 
     end 
    end 
end 

而且控制器ParticipantsController.rb

class ParticipantsController < ApiController 

    before_action :require_login, :only => [:create_participant, :update_participant] 

    # Creates a participation of a person in the event 
    # Receives the following params: 
    # - +event_id+ 
    # - +in_team+::_boolean 
    # - +event_role+ 
    def create_participant 
     # … some logic 
     if participant.save 
      render :status => :ok, :json => Hash[ 
       :participant_id  => participant.id, 
       :team_participant_id => participant.team_participant_id 
      ] 
     else 
      render :status => 406, :json => Hash[ 
       :message => t('alerts.error_saving'), 
       :errors => participant.errors.as_json 
      ] 
     end 
    end 
end 

我已经看到了控制器规格全响应对象,但是看着the code,它似乎ActionDispatch::IntegrationTest代码仅返回response.status,而不是整个响应对象。

The documentation并不直接说你可以访问响应对象。你可以尝试做一个render_views,看看这是否有什么区别,但是根据对代码的检查,看起来好像不会。