简体   繁体   中英

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.

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.


Alternative 1

Don't stub the session, instead use a testing framework like Capybara that sets up a cookie jar for you. Use an RSpec shared_context with before and after blocks that run the login.

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:

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

Using Rack::Test , look at this answer

Alternative 3

Here are the authentication helpers , so you should stub logged_in? to return true and current_account to return the user double (whether that's from FactoryGirl or a let or wherever). 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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