vendredi 28 avril 2017

Rails 4.2 Integration Tests - Is there any way to reuse test code?

If I start off with a test that checks the user can login:

test "can login successfully" do
  get "/session/new"
  assert_select "h1", "Log in to the Portal"
  assert_response :success
  post "/session", { username: "nick1", password: "password1" }
  assert_response :redirect
  follow_redirect!
  assert_select "h1", "Welcome to the Portal"
end

And in the rest of my tests, I want to test things that depend on the user to being logged in - I obviously don't want to be copying the above code into every test that requires the user to be logged in.

In my case, simulating a logged in user is simply a case of setting a session[:user_id] so I had a look around at setting session data inside the test but it appears to be very tricky. This leads me to think that maybe I could put the above code in some kind of re-usable function and call it from any test that needs a logged in user.

Does this sound like the right approach? if not, how is this problem normally solved?

Aucun commentaire:

Enregistrer un commentaire