Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Last active August 3, 2016 20:15
Show Gist options
  • Save chrisnicola/597725f548287f7e6f129567e8ab6f62 to your computer and use it in GitHub Desktop.
Save chrisnicola/597725f548287f7e6f129567e8ab6f62 to your computer and use it in GitHub Desktop.
Instance Eval'd blocks for ActionDispatch::Integration::Runner#open_session
class ActionDispatch::IntegrationTest
# Override Rails open_session so we can use an instance involved block
# instead of passing the session instance and using it. This allows the block
# to work exactly the same as the regular test.
def open_session(&block)
return super if block.nil? || block.arity > 0
super do |session|
session.instance_eval(&block)
end
end
# Helper method for login that uses the instance_eval'd block
def login(email, password = 'password')
open_session do
post sessions_url, params: { email: email, password: password }
assert_response :success, "Unable to login for #{email}:#{password}"
yield if block_given?
end
end
end
# This is what the test looks like with the instance_eval'd block
class UsersControllerTest < ActionDispatch::IntegrationTest
test 'Staff can show a user' do
user = users(:staff)
login(user.email) do
get user_url(id: users(:user).id)
assert_response :success
end
end
end
# This is what the test and helper look like with the regular session argument block,
# while it is arguably not significantly more complicated it is inconsistent with any
# test code that is written outside of an open_session block.
class UsersControllerTest < ActionDispatch::IntegrationTest
def login(email, password = 'password')
open_session do |session|
session.post sessions_url, params: { email: email, password: password }
session.assert_response :success, "Unable to login for #{email}:#{password}"
yield session if block_given?
end
end
test 'Staff can show a user' do
user = users(:staff)
login(user.email) do |session|
session.get user_url(id: users(:user).id)
session.assert_response :success
end
end
end
@chrisnicola
Copy link
Author

Obviously in an actually implementation you would just change the implementation ActionDispatch::Integration::Runner#open_session. But for the purpose of doing this in test_helper.rb I decided to just override it in the test base class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment