这里是应用程序控制器文件(application_controller.rb)中的http基本身份验证

before_filter :authenticate

protected

def authenticate
  authenticate_or_request_with_http_basic do |username, password|
    username == "username" && password == "password"  
  end
end

以及my home控制器索引操作的默认测试(spec/controllers/home_controller_spec.rb)

require 'spec_helper'

describe HomeController do

describe "GET 'index'" do
  it "should be successful" do
    get 'index'
    response.should be_success
  end
end

由于身份验证方法,测试未运行.我可以 comments "before_filter:authenticate"来运行它们,但我想知道是否有办法让它们使用该方法.

非常感谢.

推荐答案

Update(2013):马特·康诺利(Matt Connolly)提供了一个要点,也适用于请求和控制器规格:http://gist.github.com/4158961


另一种方法是,如果要运行许多测试,但不想每次都包含这些测试(代码):

Create a /spec/support/auth_helper.rb file:

module AuthHelper
  def http_login
    user = 'username'
    pw = 'password'
    request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
  end  
end

In your test spec file:

describe HomeController do
  render_views

  # login to http basic auth
  include AuthHelper
  before(:each) do
    http_login
  end

  describe "GET 'index'" do
    it "should be successful" do
      get 'index'
      response.should be_success
    end
  end

end

学分here

Ruby-on-rails相关问答推荐

在控制器操作中适当使用ActiveModel Dirty

发送不调用类或模块中的私有方法

如何从 New Relic 交易中获取 TraceId?

Rails:当 id 方法为非标准时构建关联

在 Rails 6.1 升级后,作业(job)规范使用 Minitest::UnexpectedError 包装错误

显示每个 rspec 示例的运行时

如何使用 Vim 插入 ERB 标签?

从 Rails 生成 PDF

rails 模型 has_many 本身

如何在 RoR 中实现成就系统

使用回形针调整图像大小

如何让空白复选框作为假传递给参数

我如何找出为什么我不能#destroy() 记录?

Ruby on Rails 中的MySQL 服务器已经消失

在 ruby​​ on rails 中创建自定义 html 助手

如何将 ActionMailer default_url_options 的 :host 动态设置为请求的主机名?

Post.all.map(&:id) 是什么意思?

如何仅使用 PostgreSQL 创建简单的模糊搜索?

资源和资源方法之间的区别

Ruby on Rails Bootstrap Glyphicons 不工作