rspec - How to test a customized not_found route in rails -
i have following situation:
edited
in routes.rb
namespace :api, defaults: { format: :json } namespace :v1 # definitions of other routes of api # ... match '*path', to: 'unmatch_route#not_found', via: :all end end
edited
my controller:
class api::v1::unmatchroutecontroller < api::v1::apicontroller def not_found respond_to |format| format.json { render json: { error: 'not_found' }, status: 404 } end end end
my test shown:
require 'rails_helper' rspec.describe api::v1::unmatchroutecontroller, type: :controller describe 'get response unmatched route' before :not_found, format: :json end 'responds 404 status' expect(response.status).to eq(404) end 'check json response' expect(response.body).to eq('{"error": "not_found"}') end end end
it seems right me, got same error both it
statments:
1) api::v1::unmatchroutecontroller response unmatched route responds 404 status failure/error: :not_found, format: :json actioncontroller::urlgenerationerror: no route matches {:action=>"not_found", :controller=>"api/v1/unmatch_route", :format=>:json} # /home/hohenheim/.rvm/gems/ruby-2.3.1@dpms-kaefer/gems/gon-6.1.0/lib/gon/spec_helpers.rb:15:in `process' # ./spec/controllers/api/v1/unmatch_route_controller_spec.rb:14:in `block (3 levels) in <top (required)>'
edited
the purpose route trigged when there's no other route possible in api, custom json 404 response. route , controller working expected right now, when access routes like: /api/v1/foo
or /api/v1/bar
how can write tests properly?
additional info: rails 4.2.6, rspec 3.5.4
if try write routes spec, won't work , return strange.
failure/error: expect(get("/unmatch")). route_to("unmatch_route#not_found") recognized options <{"controller"=>"unmatch_route", "action"=>"not_found", "path"=>"unmatch"}> did not match <{"controller"=>"unmatch_route", "action"=>"not_found"}>, difference:. --- expected +++ actual @@ -1 +1 @@ -{"controller"=>"unmatch_route", "action"=>"not_found"} +{"controller"=>"unmatch_route", "action"=>"not_found", "path"=>"unmatch"}
beside action not_found, returned path => unmatch maybe why controller spec didn't work expected. instead of controller test can use request test below.
require 'rails_helper' rspec.describe "get response unmatched route", :type => :request before '/not_found', format: :json end 'responds 404 status' expect(response.status).to eq(404) end 'check json response' expect(response.body).to eq('{"error": "not_found"}') end end
Comments
Post a Comment