开发者

rails + rspec : Staying DRY when testing validations

Ok say I have the following model:

class Country < ActiveRecord::Base
  va开发者_StackOverflowlidates_presence_of :name
  validates_presence_of :code
end

I'm doing the rspec unit tests for those 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

This doesn't look quite DRY. Is there any gem or plugin that automates this kind of stuff? I'd like to get something along these lines:

  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


There are remarkable for that : http://github.com/carlosbrando/remarkable

After you can do

it { should validate_presence_of :name }


If you're using factory_girl, you can do:

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

One suggestion... don't use the keyword "should" on every spec. Instead, write: "is invalid without a name"


Try also accept_values_for gem. It allows 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜