0

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
6
  • what exactly is the problem here? You're unfamiliar with rspec syntax? Unit-testing in general? Commented Oct 6, 2017 at 12:42
  • @SergioTulentsev I'm new to rspec. It's being 2-3 days only with rspec. I'm looking for syntax like "expect(user).to be saved" if it's a valid user. and how to test "BCrypt::Engine.generate_salt". I mean to say how to test BCrypt should generate salt and then hash Commented Oct 6, 2017 at 12:46
  • Why do you think you need to test BCrypt methods? This lib is heavily tested by its developers. No need to duplicate the effort. You may check that correct methods have been called, though. expect(BCrypt::Engine).to receive(:generate_salt).and_call_original, for example. Commented Oct 6, 2017 at 12:52
  • @SergioTulentsev ok got it. I will not test Bcrypt but how to write test case for rest part? Commented Oct 6, 2017 at 12:56
  • 3
    "how to write test case for rest part" - people literally write entire books on this topic :) Commented Oct 6, 2017 at 12:57

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@ashish gupta if this helped, can you mark this as the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.