session 在某些 rspec 文件中可用,而在其他文件中不可用.怎么来的? [英] session available in some rspec files and not others. how come?

查看:33
本文介绍了session 在某些 rspec 文件中可用,而在其他文件中不可用.怎么来的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试测试某些登录/退出功能时,我想从会话中删除一些信息.我发现我根本无法访问会话.我不断收到错误消息:nil:NilClass 的未定义方法`session'.

In trying to test some sign-in/out functionality I want to delete some information from the session. I found out I couldn't access the sessions at all. I kept getting the error: undefined method `session' for nil:NilClass.

但令我惊讶的是,我发现我可以从其他 rspec 页面访问会话.其他详细信息如下.我的问题是:为什么我可以从某些文件而不是其他文件访问会话?我如何才能在下面的第二个示例中访问会话?

But then to my surprise I found out I could access session from other rspec pages. Additional details are below. My question is: Why can I access session from some files and not others? And how can I make it so that I can access session in my second example below?

详情文件:spec/controllers/tenants_controller_spec.rb

Details File: spec/controllers/tenants_controller_spec.rb

require 'spec_helper'

describe TenantsController do
  specify { session[:tag].should == 'abc' }
end

文件:spec/requests/test.rb

File: spec/requests/test.rb

require 'spec_helper'

describe 'Test' do
  specify { session[:tag].should == 'abc' }
end

当我通过 rspec 运行第一个文件时,我得到:

When I run the first file through rspec I get:

Failure/Error: specify { session[:tag].should == 'abc' }
  expected: "abc"
    got: nil (using ==)

哪个好.由于这个原因,这应该会失败.

Which is good. This should fail for that reason.

但是,当我运行第二个文件时,我得到:

But, when I run the second file, I get:

 Failure/Error: specify { session[:tag].should == 'abc' }
 NoMethodError:
   undefined method `session' for nil:NilClass

那么为什么 session 在这里是一个未定义的方法?

So why is session an undefined method here?

推荐答案

您的第二个测试是一个请求"规范,它是一个集成测试.这些旨在模拟浏览器和您获得的帮助程序,您可以单击按钮并填写表单并断言页面上的文本和标签.这是检查会话对象的错误抽象级别.

Your 2nd test is a "request" spec which is an integration test. These are designed to simulate the browser and the helpers you get let you click buttons and fill out forms and assert text, tags on the page. It's the wrong level of abstraction for inspecting the session object.

如果您想取消身份验证,例如最好通过应用程序.见,例如此处:在请求规范中存根身份验证

If you want to stub out authentication, e.g. best to go through the app. See, e.g. here: Stubbing authentication in request spec

知道集成测试是探索性"或冒烟"测试,是检查组件之间接缝的高级测试,而不是组件本身的内部结构.它们的编写和维护成本最高.使用控制器规范来验证会话内容,并将所有业务逻辑移至最容易测试的模型.

Know that integration tests are "exploratory" or "smoke" tests, high level tests that check the seams between components, not the guts of the components themselves. They're the most expensive to write and maintain. Use controller specs for verifying session stuff and move all business logic to the models where it's easiest to test.

这篇关于session 在某些 rspec 文件中可用,而在其他文件中不可用.怎么来的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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