Using rails' “post” in controller tests in rsp

2019-07-07 09:01发布

I have a rails project that is running out of a subdirectory of the base url in production and I want it to act that way in dev so as to make dev and prod as close as possible. I have the routes file set up like so:

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

My CatsController is like this:

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

I want to test my Create Cat Method, so I set up an rspec test in spec/controllers/cats_controller_spec.rb:

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

When I run my test, though, I get

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

Rake routes says my route is there! What is going on under the hood here, and why is this failing?

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

2条回答
Animai°情兽
2楼-- · 2019-07-07 09:04

The problem is that the value of :protocol is a bit wonky.

The better way to fix this, I think, is to set the protocol in your scopes to http instead of http://. If you did need to test your controller with some funky protocol, though, you should be able to do:

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

or whatever your protocol might be.

查看更多
聊天终结者
3楼-- · 2019-07-07 09:31

For rspec 3, this below works for me.

post :action, protocol: 'https://'
查看更多
登录 后发表回答