3

我想实现该方法User.calculate_hashed_password。我正在尝试使用与 Rails 的内置测试工具一起使用的 Shoulda 测试库,因此与 Test::Unit 相关的答案与与 Shoulda 相关的答案一样好(我认为)。

我试图弄清楚需要测试什么以及我应该如何测试它。我最初的想法是做类似...

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

这是正确的方法吗?

4

4 回答 4

8

您无需测试该方法是否存在,只需测试该方法的行为是否正确。说这样的话:

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

(我不使用 shoulda,所以请原谅任何明显的语法错误。)

如果该方法不存在,该测试将失败。

于 2009-01-31T00:42:15.863 回答
5

我同意奥托的观点;但正如 dylanfm 所指出的,我使用 #respond_to 来测试 RSpec 中的关联。

it "should know about associated Projects" do
  @user.should respond_to(:projects)
end
于 2009-01-31T14:55:44.783 回答
3

也许使用respond_to?

于 2009-01-31T00:33:31.760 回答
0

您应该检查Object#respond_to?和新版本的 Rails 中的Object#try 。如果您是一般测试的新手,请务必通读这份出色的 Rails 测试指南

于 2009-02-03T21:01:37.600 回答