使用 RSpec 测试单一资源控制器 [英] Testing singular resource controller with RSpec

查看:42
本文介绍了使用 RSpec 测试单一资源控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 routes.rb 中定义了一个单一的资源,它看起来像这样

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

现在我正在尝试使用 RSpec 进行测试

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}

我做错了什么?

推荐答案

改变你的路线

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

这篇关于使用 RSpec 测试单一资源控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆