简体   繁体   English

为什么Rails测试环境中的机架env哈希是空的?

[英]Why is the rack env hash empty in Rails test environment?

In my Rails app, I'm accessing the env hash in one of my controller actions. 在我的Rails应用程序中,我正在访问我的一个控制器操作中的env哈希。

Something along the lines of: 有点像:

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

This works great for my requirements. 这对我的要求非常有用。

If I start my Rails app in test environment, and visit an action like: 如果我在测试环境中启动我的Rails应用程序,并访问如下操作:

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

Then the content of the env hash is output to the console as expected. 然后,env哈希的内容按预期输出到控制台。

When I get this action from within an RSPec example, the output is an empty hash? 当我从RSPec示例中获取此操作时,输出是空哈希?

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

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

Why is the env hash empty? 为什么env哈希是空的?

I've built a dummy rails app to show this 我已经构建了一个虚拟轨道应用来展示这一点

use 采用

request.env

instead of just env within the controller code. 而不仅仅是控制器代码中的env。

eg/ 例如/

def index
  puts request.env.inspect
end

Hope that helps? 希望有帮助吗?

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. 另请注意:在使用github repo时,在运行服务器时,需要删除public / index.html以使根路由正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM