ruby-on-rails - 测试无法直接访问的 RSpec Controller 操作

标签 ruby-on-rails controller rspec

我有一个 Controller 无法以传统的 RESTful 方式直接访问,只能通过特定的 url 访问。

通常我习惯于在我的 Controller 规范中使用 get 和 post 来调用 Controller 操作。有没有一种方法可以通过访问特定的 url 来运行我的 Controller ?

编辑:

这是我的路线:

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

最佳答案

Controller 测试使用四个 HTTP 动词(GET、POST、PUT、DELETE),无论您的 Controller 是否是 RESTful。所以如果你有一个非 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

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

编辑

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

因此,要测试您的 Controller 操作,只需执行以下操作:

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

关于ruby-on-rails - 测试无法直接访问的 RSpec Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4227638/

相关文章:

javascript - 简单表单无法在提交时关闭模式

ruby-on-rails - 向雪球添加省略过滤器

java - 一些 Controller 的 Spring mvc 过滤器

ruby-on-rails - Rails - 查询在开发中的 View 和 Controller 中工作,但仅在生产中的 View 中工作

javascript - 如何绑定(bind)两个选择输入并为每个输入设置初始值

ruby-on-rails - 使用部署在 Heroku 上的 Redmine 和 Integrity 在 GitHub 上的私有(private)仓库上跟踪 Rails 项目

ruby Rspec。获取所有测试的列表

ruby - 如何使用带有 Rspec 和 Capybara 的验收测试单击 href

ruby-on-rails - Rspec 未定义方法 'should receive'

ruby-on-rails - 事件管理员弹出奇怪的错误