views:

268

answers:

4

I would like to implement the method User.calculate_hashed_password. I'm trying to use the Shoulda testing library which works with Rails's built-in testing tools, so an answer related to Test::Unit would be just as good as one related to Shoulda (I think).

I'm trying to figure out what I need to test and how I should test it. My initial idea is to do something like...

class UserTest < ActiveSupport::TestCase
  should 'Return a hashed password'
    assert_not_nil User.calculate_hashed_password
  end
end

Is this the right way to do it?

A: 

Maybe use respond_to?

dylanfm
+6  A: 

You don't need to test that the method exists, just that the method behaves correctly. Say something like this:

class UserTest < ActiveSupport::TestCase
  setup do
    @user = User.new
  end

  should 'Calculate the hashed password correctly'
    @user.password = "password"
    @user.hashed_password = "xxxxx" # Manually calculate it
  end
end

(I don't use shoulda, so excuse any glaring syntax errors.)

That test will fail if the method doesn't exist.

Otto
+3  A: 

I agree with Otto; but as dylanfm noted, I use #respond_to to test for associations in RSpec.

it "should know about associated Projects" do
  @user.should respond_to(:projects)
end
Matt Darby
I do that, too, just as a simple sanity check that I put the association line in the model class.
Otto
A: 

You should check out Object#respond_to? and Object#try in newer versions of Rails. If you're new to testing in general, definitely read through this excellent guide on testing in Rails.

trevorturk