假设我们与以下属性的模型联系
class Contact < ActiveRecords:Base
validates :Name, presence: true
validates :Email, presence: true
validates :Phone, presence: true
End
现在我想单独测试这些属性,而不是使用Contact.save方法来检查它是否有效,因为在这种情况下我必须创建一个单独的对象来测试每个案例。
如果我们在收到任何错误或异常时通过此属性检查,是他们的任何方式吗?
答案 0 :(得分:1)
使用shoulda gem,您可以逐个验证字段
describe Contact do
it { should validate_presence_of :Name }
it { should validate_presence_of :Email }
it { should validate_presence_of :Phone }
end
https://github.com/thoughtbot/shoulda-matchers#validate_presence_of
您还可以通过以下方式检查整个对象验证:
it { expect(FactoryGirl.build(:contact)).to be_valid }
我认为您正在使用factory_girl来构建测试数据
<强>更新强>: 假设你有一个有效的工厂。然后你可以测试没有shoulda gem
it { expect(FactoryGirl.build(:contract, :Name => '')).to be_invalid }
it { expect(FactoryGirl.build(:contract, :Email => '')).to be_invalid }
it { expect(FactoryGirl.build(:contract, :Phone => '')).to be_invalid }
更新2 : 没有factory_girl
it { expect(Contact.new(:Name => 'Bruce', :Email => 'email@example.com', :Phone => '+123123')).to be_valid }
it { expect(Contact.new(:Email => 'email@example.com', :Phone => '+123123')).to be_invalid }
it { expect(Contact.new(:Name => 'Bruce', :Phone => '+123123')).to be_invalid }
it { expect(Contact.new(:Name => 'Bruce', :Email => 'email@example.com')).to be_invalid }
答案 1 :(得分:0)
使用普通RSpec的示例:
describe Contact do
let(:contact_params) {
{
Name: 'Contact Name',
Email: 'contact@somewhere.com',
Phone: '0123456789'
}
}
it 'is valid with valid params' do
contact = Contact.new(contact_params)
expect(contact.valid?).to be_true
end
it 'is invalid when Name is missing' do
contact_params.delete(:Name)
contact = Contact.new(contact_params)
expect(contact.valid?).to be_false
end
end