Rails以状态代码406响应

时间:2017-07-10 06:33:56

标签: ruby-on-rails ruby http http-status-code-406 actiondispatch

我一直在为Ruby on Rails中的函数测试。但是,在收到状态代码:success后,测试(期望状态代码为406)失败。这是确切的故障日志:

Failure: Expected response to be a <:success>, but was <406>.
test_should_post_comment_through_token_successfully(CommentControllerTest)
test/functional/comment_controller_test.rb:271:in `block in <class:CommentControllerTest>'

我读了一些关于406回复的内容,发现它是“不可接受的”。所以我尝试设置AcceptContent-TypeAccept-LanguageAccept-Charset标题,但我没有运气。

以下是我测试的代码:

test 'should post comment through token successfully' do
  @params = {
    id: 1,
    body: "Test Comment",
    username: "Bob"
  }

  @headers = {
    "Accept" => "application/json",
    "Accept-Language" => "en-US",
    "Accept-Charset" => "utf-8",
    "Content-Type" => "application/json",
    "Token" => "abcdefg12345"
  }

  get :create_by_token, @params, @headers
  assert_response :success
end

控制器内的create_by_token功能:

def create_by_token
  @node = Node.find params[:id]
  @user = User.find_by_username params[:username]
  @body = params[:body]
  @token = request.headers['Token']
  p request.headers["Accept"]
  p request.headers["Content-Type"]
  p request.headers["Token"]

  if @user && @user.token == @token
    begin
      @comment = create_comment(@node, @user, @body)
      msg = {
        status: :created,
        message: "Created"
      }
      respond_to do |format|
        format.xml { render xml: msg.to_xml }
        format.json { render json: msg.to_json }
      end
    rescue CommentError
      msg = {
        status: :bad_request,
        message: "Bad Request"
      }
      respond_to do |format|
        format.xml { render xml: msg.to_xml }
        format.json { render json: msg.to_json }
      end
    end
  else
    msg = {
      status: :unauthorized,
      message: "Unauthorized"
    }
    respond_to do |format|
      format.xml { render xml: msg.to_xml }
      format.json { render json: msg.to_json }
    end
  end
end

我的路线:

post '/bot/comment.:format', to: 'comment#create_by_token'

我错过了一些关键的东西吗?我该如何解决这个问题?

我很乐意提供您需要的任何其他信息。

2 个答案:

答案 0 :(得分:0)

似乎这可能是respond_to do block的错误。请检查路由是否已配置为资源或资源。

更新资源而非单数,这将有助于respond_to阻止。

您也可以尝试将路线更新为/;

resources :samples, defaults: {format: :json}

答案 1 :(得分:0)

哦,傻我。我意识到在我传递的所有参数中,格式也在URL中传递。但是,在测试中我没有提到我可以传递格式为后缀(.xml.json)的URL,我不得不提到params中的format明确。这是更新的测试代码:

test 'should post comment through token successfully' do
  @params = {
    id: 1,
    body: "Test Comment",
    username: "Bob",
    format: 'json'
  }

  @headers = {
    "token" => "abcdefg12345"
  }

  post :create_by_token, @params, @headers
  assert_response :success
end

Kudos @Sowmiya带领我得出这个结论。你的回答并不完全是我需要的解决方案,但它让我思考。