繁体   English   中英

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

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

我在Padrino的admin部分添加了更多控制器,但无法锻炼如何对当前用户进行存根或与Factory Girl或Mocha进行会话。

测试需要当前会​​话的控制器操作的好方法是什么?

警告:我没有使用过Padrino,并且您还没有给出尝试使用的任何代码,因此这很笼统和模糊。


选择1

不要存根会话,而要使用像Capybara这样的测试框架来为您设置一个cookie罐。 RSpec shared_context与运行登录的beforeafter块一起使用。

我不记得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 

选择2

使用Rack::Test ,看看这个答案

选择3

这是身份验证帮助器 ,因此您应该对logged_in?存根logged_in? 返回truecurrent_account以返回用户双倍值(无论是来自FactoryGirl还是let或任何地方)。 这样,您的应用就不会从会话中索取信息。

此解决方案似乎有效

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