【问题标题】:How do you test whether a model has a given method in Rails?如何在 Rails 中测试模型是否具有给定的方法?
【发布时间】:2009-01-31 00:23:53
【问题描述】:

我想实现方法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

这是正确的做法吗?

【问题讨论】:

  • “calculate_hashed_pa​​ssword”有什么作用?生成“密码”属性的散列版本?

标签: ruby-on-rails ruby unit-testing testing shoulda


【解决方案1】:

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

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,所以请原谅任何明显的语法错误。)

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

【讨论】:

    【解决方案2】:

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

    it "should know about associated Projects" do
      @user.should respond_to(:projects)
    end
    

    【讨论】:

    • 我也这样做,只是作为一个简单的健全性检查,我将关联线放在模型类中。
    【解决方案3】:

    也许使用respond_to?

    【讨论】:

      【解决方案4】:

      您应该在较新版本的 Rails 中查看 Object#respond_to?Object#try。如果您是一般测试新手,请务必通读excellent guide on testing in Rails

      【讨论】:

        猜你喜欢
        • 2013-12-28
        • 1970-01-01
        • 2010-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多