在 rspec 中的控制器测试中使用 Rails 的“post”以及路由的范围和协议

2024-03-05

我有一个 Rails 项目,该项目在生产中从基本 url 的子目录中运行,我希望它在开发中以这种方式运行,以使开发和生产尽可能接近。我的路线文件设置如下:

Foo::Application.routes.draw do
    def draw_routes
        root :to=>'foo#home'
        resources :cats, :only=>[:create] do
    end
    if Rails.env.production?
        scope :protocol=>'http://' do
            draw_routes
        end
    else
        scope :path=>"/foo", :protocol=>'http://' do
            draw_routes
        end
    end
end

我的 CatsController 是这样的:

class CatsController < ApplicationController
    def create
        @cat = Cat.new(:name=>"Bob")
        if @cat.save()
            redirect_to root
        end
    end
end

我想测试我的 Create Cat 方法,因此我在 spec/controllers/cats_controller_spec.rb 中设置了 rspec 测试:

require 'spec_helper'
describe CatsController do
    describe "calling create cat with good data" do
        it "should add a cat" do
            expect {post(:action=>:create)}.to change(Cat, :count).by(1)
        end
    end 
end

但是,当我运行测试时,我得到

Failure/Error: post :create
     ActionController::RoutingError:
       No route matches {:controller=>"cats", :action=>"create"}
     # ./spec/controllers/cats_controller_spec.rb:5:in `(root)'

Rake 路线说我的路线就在那里!这里到底发生了什么,为什么会失败?

Rake Routes:
    cats POST   /foo/cats(.:format)            cats#create {:protocol=>"http://"}

问题是 的值:protocol有点靠不住。

我认为解决这个问题的更好方法是将范围中的协议设置为http代替http://。不过,如果您确实需要使用一些时髦的协议来测试您的控制器,您应该能够执行以下操作:

post(:action => :create, :protocol => 'funky')

或者无论你的协议是什么。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 rspec 中的控制器测试中使用 Rails 的“post”以及路由的范围和协议 的相关文章

随机推荐