ruby on rails - Handle authentication with Capybara / Minitest for integration testing -
i'm stuck trying create integration tests using capybara , minitest::spec. i'm not using 3rd party plugin authentication. i'm using basic authentication using has_secure_password built rails 4.1
i have helper looking current_user created after authentication (pretty standard).
i've tried authenticating capybara testing visit:
test.rb
require 'test_helper' describe "admin area integration" setup def current_user create(:admin_user, password: "test", password_confirmation: "test") end end teardown current_user.destroy! end # results in error below "visits admin area path" visit admin_area_path page.text.must_include('dashboard') end # test passes "test user login" visit "/login" within("#login_form") fill_in('email', with: current_user.email) fill_in('password', with: "test") end click_button('login') has_content?('welcome') end end error
undefined method `email' nil:nilclass app/helpers/application_helper.rb is there way pass current_user object using capybara visit or missing simple helper not throw error?
you not supposed modify internals of rails app, when doing integration tests. these tests should simulate real world behaviour - user visiting site browser. there no way pass current_user object capybara, there no way modify user session user outside app.
the straightforward way extracting login steps(filling out form) separate function within other test file( have them in test/support/** , require supporting functions in spec_helper). repeat login steps before other test, requires user logged in.
however once have tested login, can rely on , repetitive task of login user each time can become quite annoying. wouldn't ruby otherwise, when there wasn't way patch app behaviour, while in test mode.
you can try using mocking/stubbing lib , stub current_user method on instance of class holding it. mocha example:
require 'mocha' applicationcontroller.any_instance.stubs(:current_user).returns(user.new {...}) the other option modify rack session directly. expect storing user_id in session, , current_user method loads user id. can require rack_session_accessgem within testsuite , set user_id of test user.
remember disable transactional fixtures @ least integration tests , use database_cleaner instead. otherwise capybara not able see of test data created, because in uncommitted transaction accessible initiating thread.
see configuring database_cleaner rails, rspec, capybara, , selenium
Comments
Post a Comment