Reputation: 3
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
Upvotes: 0
Views: 180
Reputation: 487
This may not be "an answer" per se but some comments/advice that might help point you in the right direction:
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.
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.
You probably don't need to call user.valid?. Just call user.save
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
Upvotes: 2