【问题标题】:Request in Rails Testing not returning bodyRails 测试中的请求不返回正文
【发布时间】:2016-05-31 22:28:56
【问题描述】:

我开始在 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

登录成功,但之后,当尝试创建参与者时,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

【问题讨论】:

    标签: ruby-on-rails request integration-testing


    【解决方案1】:

    我在控制器规格上看到了完整的响应对象,但查看the code,似乎ActionDispatch::IntegrationTest 代码只返回response.status,而不是整个响应对象。

    The documentation 并没有直接说您可以访问响应对象。您可以尝试执行render_views 并查看是否有任何区别,但根据对代码的检查,它似乎不会。

    【讨论】:

      猜你喜欢
      • 2017-08-14
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2014-10-31
      • 1970-01-01
      相关资源
      最近更新 更多