在 Rails 中如何测试模型是否具有给定方法?
我想实现方法User.calculate_hashed_password
。 我正在尝试使用 Shoulda 测试库,它与 Rails 的内置测试工具配合使用,因此与 Test::Unit 相关的答案与与 Shoulda 相关的答案一样好(我认为)。
我试图弄清楚我需要测试什么以及应该如何测试它。 我最初的想法是做一些类似的事情...
class UserTest < ActiveSupport::TestCase
should 'Return a hashed password'
assert_not_nil User.calculate_hashed_password
end
end
这是正确的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不需要测试该方法是否存在,只需测试该方法的行为是否正确即可。 可以这样说:(
我不使用 Shoulda,所以请原谅任何明显的语法错误。)
如果该方法不存在,则该测试将失败。
You don't need to test that the method exists, just that the method behaves correctly. Say something like this:
(I don't use shoulda, so excuse any glaring syntax errors.)
That test will fail if the method doesn't exist.
我同意奥托的观点; 但正如 dylanfm 所指出的,我使用 #respond_to 来测试 RSpec 中的关联。
I agree with Otto; but as dylanfm noted, I use #respond_to to test for associations in RSpec.
也许使用
respond_to?
Maybe use
respond_to?
您应该查看 Object#respond_to? 和 Object#try Rails 的版本。 如果您不熟悉一般测试,请务必阅读有关 Rails 测试的优秀指南。
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.