简体   繁体   中英

Ruby on Rails: How can I sign in with devise inside of my tests?

I'm having issues signing into Devise in my tests. I'm using the default testing suite in Rails.

In my test helper file, I've defined a log_in method like so:

  def log_in
    @user = User.create(id: 1)
    sign_in(:user, @user)
  end

I don't get any errors, the method just doesn't sign me in. I know this because I redirect the user when they are not signed in, and the result of one of my tests is:

ContentsControllerTest#test_should_show_content [E:/Uni/coursework/empire/test/controllers/contents_controller_test.rb:32]:
Expected response to be a <success>, but was <302>

sign_in is called in setup like so...

  setup do
    @content = contents(:one)
    log_in
  end

Any help on how I can sign in would be most appreciated.

You also should

include Devise::TestHelpers

Here you have some code samples Minitest+Devise

I've fixed my issues by changing my log_in method to the following:

  def log_in
    sign_in(users(:one))
  end

The reason why I wasn't using a fixture in the first place was because I had an issue with the fixture which was causing some strange errors. Always check your fixtures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM