简体   繁体   English

如何测试需要当前会​​话的控制器动作?

[英]How to test controller actions that require a current session?

I'm adding more controllers to the admin section of the Padrino but I can't workout how to stub the current user or a session with Factory Girl or Mocha. 我在Padrino的admin部分添加了更多控制器,但无法锻炼如何对当前用户进行存根或与Factory Girl或Mocha进行会话。

What is a good way for testing controller actions that need a current session? 测试需要当前会​​话的控制器操作的好方法是什么?

Caveat: I've not used Padrino, and you've not given any code you've tried, so this is quite general and vague. 警告:我没有使用过Padrino,并且您还没有给出尝试使用的任何代码,因此这很笼统和模糊。


Alternative 1 选择1

Don't stub the session, instead use a testing framework like Capybara that sets up a cookie jar for you. 不要存根会话,而要使用像Capybara这样的测试框架来为您设置一个cookie罐。 Use an RSpec shared_context with before and after blocks that run the login. RSpec shared_context与运行登录的beforeafter块一起使用。

I don't remember the exact syntax for Capybara and I'll leave you to look it up, but it would be something like this: 我不记得Capybara的确切语法,我将让您查找它,但这将是这样的:

shared_context "When logged in" do
  before do
    visit "/login"
    fill_in "username", user.name
    fill_in "password", user.password
    click "login!"
  end
  after do
    # log out…
  end
end

describe "Something that you need to be logged in for" do
  let(:user) { OpenStruct.new({name: "blah", password: "blurgh" }) }
  include "When logged in"
  before do
    visit "/only/authenticated/see/this"
  end
  subject { page }
  it { should be_ok }
  it { #… }
end 

Alternative 2 选择2

Using Rack::Test , look at this answer 使用Rack::Test ,看看这个答案

Alternative 3 选择3

Here are the authentication helpers , so you should stub logged_in? 这是身份验证帮助器 ,因此您应该对logged_in?存根logged_in? to return true and current_account to return the user double (whether that's from FactoryGirl or a let or wherever). 返回truecurrent_account以返回用户双倍值(无论是来自FactoryGirl还是let或任何地方)。 That way your app won't ask for the information from session. 这样,您的应用就不会从会话中索取信息。

This solution seem to work 此解决方案似乎有效

def set_current_user(user)
    ApplicationController.stub(:current_user).and_return(user)
    session[:identity_id] = user.id
end

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

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