Skip to content

Instantly share code, notes, and snippets.

@Rodrigora
Created September 19, 2015 21:50
Show Gist options
  • Save Rodrigora/440220a2e24bd42b7b0c to your computer and use it in GitHub Desktop.
Save Rodrigora/440220a2e24bd42b7b0c to your computer and use it in GitHub Desktop.
Helper for requests specs with authenticity token
module RequestMacros
def login_user(user = nil)
user = create(:user, password: 'password') unless user
# ensure password is valid when `user` is provided
expect(user.valid_password?('password')).to be(true)
# ensure user is confirmed
user.confirm!
# get the authenticity_token
get user_session_path
authenticity_token = retrieve_authenticity_token
# login
post user_session_path, 'user[email]' => user.email, 'user[password]' => 'password',
'authenticity_token' => authenticity_token
get response.headers['Location']
retrieve_authenticity_token
end
def retrieve_authenticity_token
form_authenticity_token || header_authenticity_token ||
raise("authenticity_token not found: #{response.body}")
end
def put_with_token(path, params, token = nil)
put path, params.merge('authenticity_token' => (token || retrieve_authenticity_token))
end
def post_with_token(path, params, token = nil)
post path, params.merge('authenticity_token' => (token || retrieve_authenticity_token))
end
def form_authenticity_token(body)
regex = /name="authenticity_token" type="hidden" value="(?<token>.+)"/
parts = response.body.match(regex)
parts['token'] if parts
end
def header_authenticity_token(body)
regex = /meta content="(?<token>.+)" name="csrf-token"/
parts = response.body.match(regex)
parts['token'] if parts
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment