问题
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