Rack test fails: No response yet for JSON request

╄→гoц情女王★ 提交于 2019-12-07 11:52:42

问题


I am trying to create a JSON API for my Ruby project following the Ticketee example provided in Yehuda Katz's book Rails 3 in Action, chapter 13. Here is an RSpec test described on page 353 adapted to my environment.

# /spec/api/v1/farms_spec.rb # Reduced to the minimum code.
require "spec_helper"
include ApiHelper # not sure if I need this

describe "/api/v1/farms", type: :api do
    context "farms viewable by this user" do
        let(:url) { "/api/v1/farms" }
        it "json" do
            get "#{url}.json"
            assert last_response.ok?
        end
    end
end

When I run the test I get the following output ...

$ rspec spec/api/v1/farms_spec.rb
No DRb server is running. Running in local process instead ...
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}
  1) /api/v1/farms farms viewable by this user json
     Failure/Error: assert last_response.ok?
     Rack::Test::Error:
       No response yet. Request a page first.
     # ./spec/api/v1/farms_spec.rb:30:in `block (3 levels) in <top (required)>'

Finished in 2.29 seconds
1 example, 1 failure

Here is the helper module I use ...

# /support/api/helper.rb
module ApiHelper
    include Rack::Test::Methods

    def app
        Rails.application
    end
end

RSpec.configure do |config|
    config.include ApiHelper, type: :api
end

Note: This question is similar to Testing REST-API responses with Rspec and Rack::Test.


回答1:


Rspec-rails seems to ignore the type: :api parameter of the describe block and treats all specs in /spec/api as request specs (see chapter request specs here). Maybe the type-parameter is deprecated? I haven't found any documentation for it yet..

I can get your example to work when using type: :request instead of type: :api. I also removed the app-method as it's already included in the RequestExampleGroup by default.

# /support/api/helper.rb
module ApiHelper
    include Rack::Test::Methods
end

RSpec.configure do |config|
    config.include ApiHelper, type: :request
end

And the spec:

#/spec/api/v1/farms_spec.rb 
require "spec_helper"

describe "/api/v1/farms" do
    context "farms viewable by this user" do
        let(:url) { "/api/v1/farms" }
        it "json" do
            get "#{url}.json"
            assert last_response.ok?
        end
    end
end


来源:https://stackoverflow.com/questions/13995342/rack-test-fails-no-response-yet-for-json-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!