Correct model test (Rspec)

Asked

Viewed 847 times

2

I created a test to validate my model and I 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

Validation returns flawlessly, but I don’t know if this code has the best practice for the proper test.

  • 2

    This link has fantastic content: http://betterspecs.org/br/

3 answers

3


Use Factories, the below follows 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

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 main amendments:

  1. The advantage of using the new instead of create is that the object will not persist in the bank and your test will be faster.
  2. You can pass a Hash for the model and do not need to keep assigning each field.
  3. the Matcher be_valid already calls the method valid? and checks if he returns true.

1

Use the Factorygirl as Elvis said, but it is recommended to use the let to make the scope of the test cleaner, in addition to some of the 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 without duplicates on account of Factorygirl. The most complete example to follow:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.