Rails + rspec: Stay DRY on validation validation

Ok, I have the following model:

class Country < ActiveRecord::Base validates_presence_of :name validates_presence_of :code end 

I am running rspec unit tests for these validations. They look like this:

  it "should be invalid without a name" do country = Country.new(@valid_attributes.except(:name)) country.should_not be_valid country.errors.on(:name).should == "can't be blank" country.name = @valid_attributes[:name] country.should be_valid end it "should be invalid without a code" do country = Country.new(@valid_attributes.except(:code)) country.should_not be_valid country.errors.on(:code).should == "can't be blank" country.code = @valid_attributes[:code] country.should be_valid end 

It does not look quite dry. Is there any gem or plugin that automates such things? I would like to get something in this direction:

  it "should be invalid without a name" do test_presence_validation :name end it "should be invalid without a code" do test_presence_validation :code end 
+4
source share
3 answers

Noteworthy for this: http://github.com/carlosbrando/remarkable

After doing

 it { should validate_presence_of :name } 
+9
source

If you use factory_girl you can do:

  it "should be invalid without a name" do FactoryGirl.build(:country, name: nil).should_not be_valid end 

One sentence ... do not use the keyword "should" for each specification. Instead, write: "void without name"

+5
source

Try accept_values_for gem. This allows you to do something like this:

 describe User do subject { User.new(@valid_attributes)} it { should accept_values_for(:email, " john@example.com ", " lambda@gusiev.com ") } it { should_not accept_values_for(:email, "invalid", nil, " a@b ", " john@.com ") } end 
0
source

Source: https://habr.com/ru/post/1304452/


All Articles