RSpec before(:each) 块中的验证错误有奇怪的行为

发布于 2024-12-04 08:53:47 字数 858 浏览 1 评论 0原文

修订:这里的错误是我在同一个哈希中存储了多个不同的模型。这是我构建数组的一种内部方式。无论如何,我对这里的错误表示歉意。以我的提问方式,根本无法回答这个问题。

所以我在控制器规范中有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌︼了一个春 2024-12-11 08:53:48

我会在您的模型定义中尝试以下操作:

class Model < ActiveRecord::Base
  STATI = %w[vacant deleted deactivated]
  ...
  validates :status, :inclusion => STATI
  ...
end

%w 是创建字符串数组的首选语法,并允许从数组定义中删除 ",

您不需要 :in => 进行包含验证。

I would try the following in your model definition:

class Model < ActiveRecord::Base
  STATI = %w[vacant deleted deactivated]
  ...
  validates :status, :inclusion => STATI
  ...
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文