[英]Ultimate DRY model rspec
我将我的模型rspec重构为尽可能“干燥”,导致类似
require 'spec_helper'
describe Model do
subject { build(:model) }
it { should be_valid }
it { should validate_presence_of(:description) }
it { should ensure_length_of(:description).is_at_least(3).is_at_most(255) }
it { should validate_presence_of(:position) }
it { should validate_numericality_of(:position).is_greater_than_or_equal_to(1) }
end
现在,每个文件都以
subject { build(:model) }
it { should be_valid }
所以,你猜对了,我也想摆脱这两行...
有什么建议么?
it { should be_valid }
测试似乎只在测试您的工厂。 这对于模型的功能并不是很重要。 如果要测试它们,请考虑将这些测试移至单个factories_spec
测试。 参见: https : //github.com/thoughtbot/suspenders/blob/master/templates/factories_spec.rb
您在示例中使用的匹配器实际上并不需要使用FactoryGirl构建的模型。 它们可以与隐式默认主题(Model.new)配合使用。 如果不是这种情况,我建议您在测试内部定义尽可能多的测试状态,也就是在it
块内部。 如果那导致某些重复,那就这样吧。 可以将特别昂贵的复制提取到方法调用中,这种方法比subject
, let
和before
let
可取,因为它们没有魔力。 当开发人员在6个月内回到该项目时,请查看第75行的规范,您将确切了解设置是什么。
您可以使用rspec 共享的示例 :
shared_examples "a model" do
subject { build described_class }
it { should be_valid }
end
describe Foo do
it_behaves_like "a model"
end
describe Bar do
it_behaves_like "a model"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.