我对TDD比较陌生,我正在编写一个单元测试,以确保wishlist
无法保存而没有相应的user
。这是我的礼品单模型类:
class Giftlist < ApplicationRecord
belongs_to :user
end
这是我的用户模型类:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :giftlists
end
我的测试看起来像这样:
test 'wishlist must have an associated user' do
@giftlist = Giftlist.new
assert_not @giftlist.save, 'wishlist was saved without user'
end
由于我没有将validates :user, presence: true
添加到我的心愿单模型中,因此我期待此测试失败。然而,测试通过使我相信rails对外键关联做了一些隐式验证。
这是发生了什么事吗?或者还有其他事情发生了吗?
答案 0 :(得分:1)
我觉得使用Shoulda Matchers更容易表达这种行为。有了它,您可以简洁地编写您的行为和期望,而无需做任何样板。
it { is_expected.to belong_to(:user) }
但是,你的直接问题似乎是对assert_not
的不当使用。 assert_not
,在我阅读文档时,否定您正在评估的表达式(并将nil
变为true
)。
在这种情况下,您希望断言测试对象 成功保存,否则打印出错误消息。
test 'wishlist must have an associated user' do
@giftlist = Giftlist.new
assert @giftlist.save, 'wishlist was saved without user'
end