ruby-on-rails - 在 rspec 请求规范中使用请求方法

标签 ruby-on-rails ruby rspec

我正在尝试使用 rspec 测试多个 Controller 之间的场景。

我认为“请求规范”是我应该使用的方法。

主要问题是我使用请求环境使用基本身份验证登录。

我的 Controller 测试运行良好:

describe ClientsController do
  context "With a confirmed user" do
    before(:each) do
      @password = "bidon-bidon"
      @user = ...
    end

    it "should create session" do
      request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, @password)
      post :create
      response.should be_success
    end
  end
end

但是当我在我的文件 spec/requests/scenario_spec.rb 中使用方法 request 时,它引发了一个异常:

describe "My scenario" do
  context "With a confirmed user" do
    before(:each) do
      ...
    end

    it "should do several things"
      request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, @password)
      post :create
      response.should be_success

      ... some calls to other controllers
    end
  end
end

request 方法似乎返回nil

NoMethodError:  undefined method `env' for nil:NilClass

我的问题是:

  • 在哪里可以找到有关request 方法的文档?
  • 如何设置?

我正在使用带有 Rspec 2.14.7 的 Rails 4。

最佳答案

取自这个问题 - Is it possible to specify a user agent in a rails integration test or spec?

尝试:

it "should do several things"
  post :create, {}, 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(@user.login, @password)
  response.should be_success

  ... some calls to other controllers
end

关于ruby-on-rails - 在 rspec 请求规范中使用请求方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22451020/

相关文章:

ruby - 从 require 获取数据库配置

ruby-on-rails - Rails 获取 "each"循环的索引

ruby-on-rails - 如何继续运行 Capistrano 2

ruby-on-rails - cucumber 和 rspec 可以使用相同的 blueprints.rb 文件吗

ruby-on-rails - rspec-core 中的 find_failed_line 错误

ruby-on-rails - 仅 Rails 渲染布局?

ruby-on-rails - 有什么方法可以知道是否对网站进行了任何分析?

ruby-on-rails - rails - 根模型或应用程序模型

ruby-on-rails - 如何阻止谷歌搜索链接到 https?

rspec - Capybara 无法通过 id 找到元素