Correct test for model (RSpec)

2

I created a test to validate my model and want to know if it is correct.

describe Article do
  it "object article create is valid?" do
        article = Article.create
        article.title = "Title for Test"
        article.description = ""
        article.body = "Body for Test"
        article.position_image_highlighted = ""

        expect(article.valid?).to be
    end
end

The validation returns without fail, but I do not know if this code has the best practice for the due test.

    
asked by anonymous 30.01.2014 / 14:50

3 answers

3

Use Factories , below is a very simple example. Take a look at the new way of writing expects in RSpec.

describe Article do
  it "expect valid article" do
    article = FactoryGirl.create(:article)    
    expect(article).to be_valid          
  end
end

Factory:

FactoryGirl.define do
  factory :article do
    title "Title for Test"
    description ""
    body "Body for Test"
    position_image_highlighted = ""
  end
end
    
30.01.2014 / 15:06
1
describe Article do
  it "object article create is valid?" do
    article = Article.new({ # 1
      title: "Title for Test", # 2
      description: "",
      body: "Body for Test",
      position_image_highlighted: ""
    })

    expect(article).to be_valid # 3
  end
end

Three major changes:

  • The advantage of using new instead of create is that the object will not be persisted in the database and your test will be faster.
  • You can pass Hash to the model and you do not need to assign each field.
  • Matcher be_valid already calls the valid? method and checks to see if it returns true .
  • 30.01.2014 / 19:00
    1

    Use FactoryGirl as Elvis said, however, it is recommended to use let to make the scope of the test cleaner, as well as some other advantages cited in BetterSpecs .

    My suggestion is:

    FactoryGirl

    FactoryGirl.define do
      factory :article do
        title 'Title for Test'
        description ''
        body 'Body for Test'
        position_image_highlighted = ''
      end
    end
    

    Spec:

    describe Article do
      let(:article) { FactoryGirl.build(:article) }
    
      it 'is a valid article' do
        expect(article).to be_valid          
      end
    end
    

    And to test an invalid article would be simpler and no duplication on account of FactoryGirl. The most complete example below:

    describe Article do
      context 'with required fields' do
        let(:article) { FactoryGirl.build(:article) }
    
        it 'is a valid article' do
          expect(article).to be_valid          
        end
      end
    
      context 'with no title' do
        let(:article) { FactoryGirl.build(:article, title: '') }
    
        it 'is an invalid article' do
          expect(article).to_not be_valid          
        end
      end
    end
    
        
    02.02.2014 / 21:11