M
M
Max2016-05-01 14:51:40
Ruby on Rails
Max, 2016-05-01 14:51:40

How do factories work in rspec tests?

Hello, please help me understand the logic of model tests using factories.
Here is the test itself:

require 'rails_helper'

RSpec.describe News do
  news1 = FactoryGirl.create(:news)
  news2 = FactoryGirl.create(:news)
  news1.title.should == "1 test news title"
  news2.title.should == "2 test news title"
end

Here is the factory
FactoryGirl.define do
  factory :news do
    sequence(:title) { |i| "#{i} test news title"}
    sequence(:description) { |i| "#{i} test news description, must have minimum 40 letters"}
    user_id 1
    news_poster { fixture_file_upload "#{Rails.root}/spec/fixtures/images/calendar.png", 'image/png' }
  end
end

And the News model
class News < ActiveRecord::Base
  belongs_to :user
  has_attached_file :news_poster, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :news_poster, content_type: /\Aimage\/.*\Z/
  validates :title, presence: true, uniqueness: true, length: { minimum: 5, maximum: 40 }
  validates :description, presence: true, length: { minimum: 40, maximum: 250 }
  validates :news_poster, presence: true
end

According to my logic, every time a test is run, new records should be created in the test database with the changed number "i"
sequence(:title) { |i| "#{i} test news title"}
And when the test is run for the first time, everything works, records with titles are created - "1 test news title" and "2 test news title" - the test passes successfully, but when repeated - the numbers 1 and 2 do not changes to 3 and 4 as I thought, and an error is already popping up. Perhaps I'm not building the logic of the tests correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2016-05-01
@maxprof

Sequences are reset after each run.
Use the database_cleaner gem

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question