简体   繁体   中英

how to write test case using rspec of this method

I want to write test case for below method. I'm new to unit testing. Please let me know the correct way to write test case for below method.

def create_new_user
    self.password_salt = BCrypt::Engine.generate_salt
    self.password_hash = BCrypt::Engine.hash_secret(self.password, password_salt)
    user = User.new(email: self.email, username:self.username, password_hash: password_hash, password_salt: password_salt)
    if user.valid?
      user.save ? {is_created: true, err:''} : {is_created: false, err:'Something went wrong,please try later...'}
    else
      {is_created: false, err: 'Please enter all mandetory fields..'}
    end
  end

This may not be "an answer" per se but some comments/advice that might help point you in the right direction:

  1. Your method looks to be returning a hash even though it's creating a new user. You should probably return the new user. If there are errors, the activerecord object will have those errors, no need to add your own errors.

  2. Remember to test behavior. This is crucial to the change in point 1. The behavior of this method is: It returns a user record, either saved or not, that's the behavior. Test that.

  3. You probably don't need to call user.valid?. Just call user.save

  4. You can probably just return user.save itself, since, if it works, you'll get a user that is persisted/saved. If it doesn't you can check user.errors

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