如何在Rails中测试模型是否具有给定方法?

Eth*_*han 3 ruby testing unit-testing ruby-on-rails shoulda

我想实现这个方法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
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

Ott*_*tto 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
Run Code Online (Sandbox Code Playgroud)

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

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


Mat*_*rby 5

我同意奥托; 但正如dylanfm所说,我使用#respond_to来测试RSpec中的关联.

it "should know about associated Projects" do
  @user.should respond_to(:projects)
end
Run Code Online (Sandbox Code Playgroud)