【问题标题】:Testing an RSpec controller action that can't be accessed directly测试无法直接访问的 RSpec 控制器操作
【发布时间】:2010-11-19 17:23:41
【问题描述】:

我有一个不能直接访问的控制器,以传统的 RESTful 方式,而只能通过特定的 url。

通常我习惯在控制器规范中使用 get 和 post 来调用控制器操作。有没有办法通过访问特定的 url 来锻炼我的控制器?

编辑:

这是我的路线:

Larzworld::Application.routes.draw do

  match '/auth/:provider/callback' => 'authentications#create'

  devise_for :users, :controllers => {:registrations => "registrations"} 

  root :to => 'pages#home'
end

这是我的规格:

require 'spec_helper'

describe AuthenticationsController do

before(:each) do
  request.env["omniauth.auth"] = {"provider" => "twitter", "uid" => "12345678"} 
end

describe 'POST create' do

  it "should find the Authentication using the uid and provider from omniauth" do
    Authentication.should_receive(:find_by_provider_and_uid)
    post 'auth/twitter/callback'
  end
end

end

这是我收到的错误:

Failures:
  1) AuthenticationsController POST create should find the Authentication using the uid and provider from omniauth
    Failure/Error: post 'auth/twitter/callback'
    No route matches {:action=>"auth/twitter/callback", :controller=>"authentications"}
    # ./spec/controllers/authentications_controller_spec.rb:13

Finished in 0.04878 seconds
1 example, 1 failure

【问题讨论】:

    标签: ruby-on-rails controller rspec


    【解决方案1】:

    无论您的控制器是否为 RESTful,控制器测试都使用四个 HTTP 动词(GET、POST、PUT、DELETE)。所以如果你有一个非 RESTful 路由 (Rails3)

    match 'example' => 'story#example'
    

    这两个测试:

    require 'spec_helper'
    
    describe StoryController do
    
      describe "GET 'example'" do
        it "should be successful" do
          get :example
          response.should be_success
        end
      end
    
      describe "POST 'example'" do
        it "should be successful" do
          post :example
          response.should be_success
        end
      end
    
    end
    

    都会通过,因为路由接受任何动词。

    编辑

    我认为您混淆了控制器测试和路由测试。在控制器测试中,您要检查操作的逻辑是否正常工作。在路由测试中,您检查 URL 是否转到正确的控制器/操作,以及是否正确生成了 params 哈希。

    所以要测试您的控制器操作,只需执行以下操作:

    post :create, :provider => "twitter"`
    

    要测试路由,请使用params_from(适用于 Rspec 1)或 route_to(适用于 Rspec 2):

    describe "routing" do
      it "routes /auth/:provider/callback" do
        { :post => "/auth/twitter/callback" }.should route_to(
          :controller => "authentications",
          :action => "create",
          :provider => "twitter")
      end
    end
    

    【讨论】:

    • 好吧,我就是这么想的,但是看看我编辑过的帖子,我发布了我的路线、我的测试和我的错误。我不明白为什么它没有将其映射到正确的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多