我一直在努力成为一名合适的TDD老兄。我已经在我的模型上设置了Rspec,FactoryGirl和一些基本测试。所有这些测试都验证了我的Plantask模型的存在。
我已经把我的工厂搬到了一个前面的块,这是一些小的重构,但由于我刚接触测试,我想要一些关于如何改进我的测试的建议。我还没有足够的经验知道他们是否真的“干”。
在我的模型中:
验证:area_id,presence:true#添加等。
我的测试:
require 'spec_helper'
describe Plantask do
before(:each) do
@plantask = FactoryGirl.create(:plantask)
end
it "is valid with valid attributes" do
@plantask.should be_valid
end
it "is invalid without an area" do
@plantask.area_id = nil
@plantask.should_not be_valid
end
it "is invalid without equipment" do
@plantask.equipment_id = nil
@plantask.should_not be_valid
end
it "is invalid without a part" do
@plantask.part_id = nil
@plantask.should_not be_valid
end
it "is invalid without a description" do
@plantask.description = nil
@plantask.should_not be_valid
end
it "is invalid without a datatype" do
@plantask.datatype_id = nil
@plantask.should_not be_valid
end
it "is invalid without an assignment" do
@plantask.assigned = nil
@plantask.should_not be_valid
end
it "is invalid without an associate" do
@plantask.associate_id = nil
@plantask.should_not be_valid
end
it "is invalid without a number" do
@plantask.number = nil
@plantask.should_not be_valid
end
end
好的,谢谢你们。现在我有了这个,它更加紧凑。很酷。
require 'spec_helper'
describe Plantask do
subject (:plantask) { FactoryGirl.create(:plantask) }
it { should validate_presence_of(:area_id) }
it { should validate_presence_of(:equipment_id) }
it { should validate_presence_of(:part_id) }
it { should validate_presence_of(:description) }
it { should validate_presence_of(:datatype_id) }
it { should validate_presence_of(:assigned) }
it { should validate_presence_of(:associate_id) }
it { should validate_presence_of(:procedure_id) }
it { should validate_presence_of(:recurrence) }
it { should validate_presence_of(:number) }
it { should be_valid }
end
答案 0 :(得分:0)
对于这种测试,我建议您使用shoulda-matchers gem,它将帮助您清理代码。
这将是这样的:
it { should validate_presence_of(:area_id) }
it { should validate_presence_of(:equipment_id) }
...
答案 1 :(得分:0)
使用主题https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/subject/explicit-subject
describe Plantask do
subject (:plantask) { FactoryGirl.create(:plantask) }
it { should be_valid }
...
end