我一直在 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
响应的内容,发现它代表“不可接受”。所以我尝试设置Accept
、和标题Content-Type
,但我没有运气。Accept-Language
Accept-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'
我错过了一些重要的东西吗?我该如何解决这个问题?
我很乐意提供您需要的任何其他信息。