Question

suppose we have a model contact with the following properties

class Contact < ActiveRecords:Base
validates :Name, presence: true
validates :Email, presence: true
validates :Phone, presence: true
End

Now i want to test these properties individually ant not by using Contact.save method to check if it validates or not, as in that case i have to create a separate object to test each case.

is their any way if we check that by this property if we are getting any error or exception?

No correct solution

OTHER TIPS

Using shoulda gem you be able to validate fields one by one

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

You also be able to check whole object validation by:

it { expect(FactoryGirl.build(:contact)).to be_valid }

I suppose you're using factory_girl to build your test data

Update: Suppose you have a valid factory. Then you be able to test without 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 }

Update 2: Without 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 }

Example using plain 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top