为什么 Rails 测试环境中的 rack env 哈希是空的? [英] Why is the rack env hash empty in Rails test environment?

查看:34
本文介绍了为什么 Rails 测试环境中的 rack env 哈希是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Rails 应用程序中,我正在访问控制器操作之一中的 env 哈希值.

In my Rails app, I'm accessing the env hash in one of my controller actions.

大致如下:

def my_before_filter
  env['some.key'] = "Something or other"
end

这非常适合我的要求.

如果我在测试环境中启动我的 Rails 应用程序,并访问如下操作:

If I start my Rails app in test environment, and visit an action like:

# /users in UsersController#index
def index
  puts env.inspect
end

然后将 env 哈希的内容按预期输出到控制台.

Then the content of the env hash is output to the console as expected.

当我从 RSPec 示例中获取此操作时,输出是空哈希?

When I get this action from within an RSPec example, the output is an empty hash?

it 'should get the index action' do
  get :index
end

.....{}.... # rspec output

为什么 env 哈希是空的?

Why is the env hash empty?

我已经构建了一个 dummy rails 应用程序来展示这一点

I've built a dummy rails app to show this

推荐答案

使用

request.env

而不仅仅是控制器代码中的 env.

instead of just env within the controller code.

例如/

def index
  puts request.env.inspect
end

希望有帮助吗?

顺便说一句:在使用 github 存储库时,您需要删除 public/index.html 以使根路由在运行服务器时工作.

BTW on another note: when working with your github repo you need to delete the public/index.html for your root route to work, when running the server.

这篇关于为什么 Rails 测试环境中的 rack env 哈希是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆