问题
I have defined a singular resource in my routes.rb
which looks like this
Rails.application.routes.draw do
resource :dog, only: [:create], to: "dog#create", controller: "dog"
end
After that I've defined a controller with a create action like this
class DogController < ApplicationController
def create
render json: {}, status: :ok
end
end
And now I'm trying to test it out with RSpec like this
require "rails_helper"
describe DogController do
it "works" do
post :create, params: { foo: :bar }
end
end
This is throwing this error instead of passing:
ActionController::UrlGenerationError:
No route matches {:action=>"create", :controller=>"dog", :foo=>:bar}
What am I doing wrong?
回答1:
Change your route to
resource :dog, only: [:create], :controller => "dog"
It is better to use plural controllers even if its a singular resource
http://edgeguides.rubyonrails.org/routing.html#singular-resources
回答2:
Your create action is not taking in any parameter. It's just rendering json and returning a status code
来源:https://stackoverflow.com/questions/40978962/testing-singular-resource-controller-with-rspec