Domanda

I cannot understand, how correct use before_validation callback with Rspec.

models/category.rb

class Category < ActiveRecord::Base 
    validates_presence_of :name, :permalink
    before_validation :generate_permalink

    private
    def generate_permalink
        self.permalink = Russian.translit(name).parameterize if permalink.blank?
    end
end

category_spec.rb

describe Category do
    it { should validate_presence_of(:name) }   
    it { should validate_presence_of(:permalink) }
    it "should generate permalink" do
        category = build(:category, name: "Category name", permalink: "")
        category.valid?
        category.permalink.should eq "category-name" 
    end
end

and factories/categories.rb

FactoryGirl.define do
  factory :category do
    name "Category name"
    permalink "category-name"
  end
end

For first two tests I got errors:

undefined method `scan' for nil:NilClass
È stato utile?

Soluzione

You can check validation for an instance, not for the class itself:

it "should be invalid without a name" do
  category = build(:category, name: "some name", permalink: "some link")
  expect{ category.name = nil }.to change{ category.valid? }.to false
end

Validation of permalink presence in your code is excessive. The before_validation callback will provide non-blank value for the permalink before validation. That's why validation of permalink will never fail.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top