ruby-on-rails 如何在Rspec请求中请求特定格式?

nue99wik  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(93)

我的Playgrounds控制器的get_children方法呈现了一个特定的JavaScript模板,或JSON格式的数据:

# GET children from playground
def get_children
  @business_areas = @playground.business_areas.visible.order(:sort_code)

  respond_to do |format|
    format.json { render json: @business_areas }
    format.js # uses specific template to handle js
  end
end

字符串
当使用Rspec测试请求此方法时,我得到以下错误消息:ActionController::UnknownFormat。对于该测试,已提前创建了操场和一个子业务区域:

describe "get_children - GET /playgrounds/:id/get_children" do
    it "renders a successful response" do
      get get_children_playground_url(playground)
      expect(response).to be_successful
    end

    it "renders the expected object" do
      get get_children_playground_url(playground)
      parsed_body = JSON.parse(response.body)
      expect(parsed_body[:name][:en]).to eq('Test Business Area')
    end
  end


通过阅读,我发现了一些关于request.accept = "application/json"的参考资料,但我没有设法让它工作。
我应该如何以及在哪里设置方法调用的预期输出格式?
谢谢你的帮助!
PS:RSpec版本为3.12

kx5bkwkv

kx5bkwkv1#

describe "GET /playgrounds/:id/get_children" do
  it "renders an html response" do
    get get_children_playground_url(playground)
    expect(response.content_type).to eq "text/html; charset=utf-8"
  end

  it "renders a json response" do
    # NOTE: using Accept header
    # get get_children_playground_url(playground), headers: {Accept: "application/json"}
    # NOTE: using .json url extension
    get get_children_playground_url(playground, format: :json)
    expect(response.content_type).to eq "application/json; charset=utf-8"
  end

  it "renders a js response" do
    # get get_children_playground_url(playground), headers: {Accept: "text/javascript", HTTP_X_REQUESTED_WITH: "XMLHttpRequest"}
    # NOTE:         there is an option for all that ^                                    ^ this one is to avoid cross origin error
    get get_children_playground_url(playground), xhr: true
    expect(response.content_type).to eq "text/javascript; charset=utf-8"
  end 
end

个字符

  • https:api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html#method-i-process*

相关问题