Testing singular resource controller with RSpec

偶尔善良 提交于 2019-12-12 04:34:13

问题


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

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