简体   繁体   English

如何使用 Rspec 验证 Rails 中数组的存在?

[英]How to validate presence of an array in Rails with Rspec?

My specs work fine validating login and in that validation I have access to some_array but in the validation for some_array it fails because I don't have access to it.我的规范在验证登录时工作正常,在该验证中我可以访问some_array但在验证some_array时失败,因为我无权访问它。 Is there some special thing I need to do to test for arrays?我需要做一些特殊的事情来测试数组吗?

model模型

  validates_presence_of :login, :some_array

rspec规格

  it { should validate_presence_of(:login) }
  it { should validate_presence_of(:some_array) }

Not much info to go on so...没有太多信息要继续,所以......

What you need to think is how is the array getting set in the first place?您首先需要考虑的是数组是如何设置的? With each of those it { } blocks a brand new WhateverModel is created.对于其中的每一个,它 { } 阻止了一个全新的WhateverModel被创建。

Is Whatever.some_array populated on creation?Whatever.some_array填充上创造?

it { expect(WhateverModel.some_array).to_not eq([]) }
it { expect(WhateverModel.some_array).to be }

it { expect(WhateverModel.some_array).to be_kind_of Array }

If your "array" is some kind of model relation then there are other matchers for that.如果您的“数组”是某种模型关系,那么还有其他匹配器。

There are tons of matchers you might see something more useful in the docs: https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers您可能会在文档中看到大量匹配器: https : //relishapp.com/rspec/rspec-expectations/docs/built-in-matchers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM