gpt4 book ai didi

unit-testing - 在Rails中,有没有一种使用 `before_validation`参数测试 `:on`回调的好方法?

转载 作者:行者123 更新时间:2023-12-04 13:43:49 25 4
gpt4 key购买 nike

我的一个模型中有一个before_validation :do_something, :on => :create

我想测试这种情况是否发生,并且:save上没有不会发生

有没有一种简洁的方法来测试它(使用Rails 3,Mocha和Shoulda),而无需执行以下操作:

context 'A new User' do
# Setup, name test etc
@user.expects(:do_something)
@user.valid?
end

context 'An existing User' do
# Setup, name test etc
@user.expects(:do_something).never
@user.valid?
end

在Shoulda API中找不到任何东西,这感觉有点不干燥...

有任何想法吗?谢谢 :)

最佳答案

我认为您需要更改方法。您正在测试Rails是否在工作,而不是您的代码可以在这些测试中工作。考虑改为测试您的代码。

例如,如果我有这个相当无聊的类(class):

class User
beore_validation :do_something, :on => :create

protected

def do_something
self.name = "#{firstname} #{lastname}"
end
end

我实际上会像这样测试它:
describe User do
it 'should update name for a new record' do
@user = User.new(firstname: 'A', lastname: 'B')
@user.valid?
@user.name.should == 'A B' # Name has changed.
end

it 'should not update name for an old record' do
@user = User.create(firstname: 'A', lastname: 'B')
@user.firstname = 'C'
@user.lastname = 'D'
@user.valid?
@user.name.should == 'A B' # Name has not changed.
end
end

关于unit-testing - 在Rails中,有没有一种使用 `before_validation`参数测试 `:on`回调的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5563590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com