RSpec before(:each) 块中的验证错误有奇怪的行为
修订:这里的错误是我在同一个哈希中存储了多个不同的模型。这是我构建数组的一种内部方式。无论如何,我对这里的错误表示歉意。以我的提问方式,根本无法回答这个问题。
所以我在控制器规范中有一个 RSpec before(:each) 块。我的示例模型有一个状态字段和以下验证:
class Model < ActiveRecord::Base
STATI = [ "vacant", "deleted", "deactivated"]
...
validates :status, :inclusion => { :in => STATI }
...
end
在我的规范中,我有以下代码。
describe Controller do
...
describe "some methods" do
before(:all) do
@models = []
10.times { @models << Factory(:model) }
end
before(:each) do
@models.each { |m| m.update_attributes(:status => "vacant") }
end
...
end
end
当我运行规范时,所有其他描述块都运行良好。它会产生一个错误,其影响如下: ActiveRecord::记录无效: 验证失败:状态未包含在列表中 并指向 m.update_attributes(:status => "vacant") 所在的行。
感谢您的帮助。
REVISED: the error here was that I was storing several different models in the same hash. This was an internal way with how I was constructing the array. Anyway, I apologize for the error here. There was no way one could have answered the question with how I asked it.
So I have an RSpec before(:each) block in a controller spec. My example model has a status field and the following validation:
class Model < ActiveRecord::Base
STATI = [ "vacant", "deleted", "deactivated"]
...
validates :status, :inclusion => { :in => STATI }
...
end
And in my spec, I have the following code.
describe Controller do
...
describe "some methods" do
before(:all) do
@models = []
10.times { @models << Factory(:model) }
end
before(:each) do
@models.each { |m| m.update_attributes(:status => "vacant") }
end
...
end
end
When I run the spec, all the other describe blocks run fine. It pulls an an error to the effect of:
ActiveRecord::RecordInvalid:
Validation failed: Status is not included in the list
and points to the line where it says m.update_attributes(:status => "vacant").
Thank you for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会在您的模型定义中尝试以下操作:
%w 是创建字符串数组的首选语法,并允许从数组定义中删除
"
和,
。您不需要
:in =>
进行包含验证。I would try the following in your model definition:
The %w is preferred syntax for creating an array of strings, and allows the removal of
"
and,
from your array definition.You do not need the
:in =>
for an inclusion validation.