Jumbalaya Wanton
Jumbalaya Wanton

Reputation: 1621

Testing methods that return tokens or random values rspec

I have this method:

  def encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

I want to write a test. But what should I test for? The only thing I know is that it should not return a nil value. But that could be a false positive, no?

What's a better way to test that encrypt actually does encrypt?

  describe 'encrypt' do
    it "it returns an ecrypted token" do
      expect(subject.encrypt("hello")).not_to eq nil
    end
  end

Upvotes: 0

Views: 533

Answers (2)

Matthias Berth
Matthias Berth

Reputation: 763

You want to test the expected behavior, with a known result. Looking for an example I came across http://en.wikipedia.org/wiki/SHA-1#Example_hashes:

describe 'encrypt' do
  it "it returns an ecrypted token" do
    text = 'The quick brown fox jumps over the lazy dog'
    hex = '2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12'
    expect(subject.encrypt(text)).to eq hex
  end
end

Upvotes: 2

S. A.
S. A.

Reputation: 3754

An SHA1 hash value typically is 40 characters long. You could test the size of the returned string:

describe 'encrypt' do
  it "it returns an ecrypted token" do
    subject.encrypt("hello").size.should eq(40)
  end
end

Upvotes: 1

Related Questions