【发布时间】:2015-06-05 17:54:01
【问题描述】:
我测试的每个模型都有相同的“它必须有atribute”测试,测试validates_presence_of 的某些属性。所以,我的目标是创建一个以模块化方式包含此测试的“助手”。
这是我所拥有的:
# /spec/helpers.rb
module TestHelpers
# Runs generic validates_presence_of tests for models
def validate_presence( object, attributes=[] )
attributes.each do |attr|
it "must have a #{attr}" do
object.send("#{attr}=", nil)
expect(object).not_to be_valid
end
end
end
end
和
# /spec/rails_helper.rb
# Added
require 'helpers'
# Added
RSpec.configure do |config|
config.include TestHelpers
end
和
# /spec/models/business_spec.rb
require 'rails_helper'
RSpec.describe Business, type: :model do
describe "Validations" do
before :each do
@business = FactoryGirl.build(:business)
end
# Presence
validate_presence @business, %w(name primary_color secondary_color)
但是,我收到以下错误:
`validate_presence` is not available on an example group
我已阅读有关 shared_helpers 和使用 it_behaves_as 的信息,但我不确定这是否是我正在寻找的。也许我只是想以错误的方式这样做。
--更新--
如果我将 validate_presence 方法放入 it 块中,我会收到以下错误:
Failure/Error: it { validate_presence @business, %w(name primary_color secondary_color published) }
`it` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).
【问题讨论】:
-
验证应该在示例中,而不是在规范的序言中。
-
如果我把它放在
it块中,我会得到一个不同的错误(添加到原始帖子中) -
你不应该检查
object吗? -
戴夫,是的,但不是在这个最小的例子中。 :)
标签: ruby-on-rails ruby-on-rails-4 rspec