September 2, 2013

Testing monban authentication (the better way)

Few days ago, I've wrote a post about monban and factory girl. Well, now there is the better way how to integrate them together.

Create spec/support/monban.rb:

Monban.test_mode!

This allows you to use user.password_digest= for setting password and user.password_digest for retrieving it. Also it is faster than using BCrypt. So this is win win ;).

Then you can create factories in spec/factories.rb:

FactoryGirl.define do
  factory :user do
    username 'user'
    password_digest 'password'

    factory :admin do
      admin true
    end
  end
end

Some helpers in spec/support/sign_in_helpers.rb:

module SignInHelpers
  def sign_in_as_admin
    admin = FactoryGirl.create(:admin)
    sign_in_as admin
  end

  def sign_in
    user = FactoryGirl.create(:user)
    sign_in_as user
  end

  def sign_in_as user
    visit new_session_path
    fill_in 'Meno', with: user.username
    fill_in 'Heslo', with: user.password_digest
    click_button 'Prihlásiť'
    user
  end
end

RSpec.configure do |config|
  config.include SignInHelpers
end

And there you go! Now you can use them in your feature specs.

# sign in as non admin user
sign_in

# sign in as particular user
user = FactoryGirl.create(:user, username: 'Joe')
sign_in_as user

# sign in as admin
sign_in_as_admin

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.