在Sinatra测试中使用Rspec / Rack :: Test设置会话

时间:2015-09-15 19:17:51

标签: ruby session rspec sinatra capybara

我正在尝试测试使用oauth的Sinatra应用程序,该应用程序在回调的每个路由之前运行以下代码:

before do
  unless session.has_key?(:oauth_token) || request.path == '/auth/callback'
    access_url = oauth_client.auth_code.authorize_url(redirect_uri: ENV['CALLBACK'])
    puts "Redirecting to #{access_url}"
    redirect "#{access_url}"
  end
end

对于我的测试,我只是想将session[:oauth_token]设置为任何,以便我通过此块并进入测试。然而,经过数小时的搜索和实验,我无法弄明白。

我已尝试Rack::Test尝试以这种方式设置:

describe "Visit home page", js: true do
    before { get '/', {}, { 'rack.session' => { oauth_token: 'blahblahblah' } } }
    it "has a list of products" do
      get "/"
      expect(page).to have_link("Clear & Mild Foam Handwash Refill, Fragrance-Free, 1250mL Refill, 3/Carton")
      expect(page).to have_link("Coffee Portion Packs, 1.5oz Packs, Hazelnut Crème, 24/Carton")
    end
  end
end

我的spec_helper.rb看起来像这样:

require File.expand_path '../../server.rb', __FILE__
require 'rspec'
require 'capybara/rspec'
require 'rack/test'
require 'capybara-screenshot/rspec'
require 'capybara/poltergeist'
Capybara.javascript_driver = :poltergeist

set :environment, :test

Capybara.app = Sinatra::Application

ENV['RACK_ENV'] = 'test'

module RSpecMixin
  include Rack::Test::Methods
  def app() Sinatra::Application end

  def setup_session(session = {})
    Rack::Session::Abstract::SessionHash.stub(:new).and_return(session)
  end
end

RSpec.configure do |c|
  c.include RSpecMixin
end

在每条路线之前实际设置会话的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

试试这个:

env "rack.session", { oauth_token: 'blahblahblah' }
get '/'

取自here