Umesh Malhotra
Umesh Malhotra

Reputation: 1047

Rspec before(:each) works but before(:all) does not

My ProductCategory spec:-

require 'rails_helper'

RSpec.describe ProductCategory, type: :model do
    before(:each) do 
        @product_category = create(:product_category)
    end

  context "validations" do 
    it "should have valid factory" do
        expect(@product_category).to be_valid
    end

    it "should have unique name" do 
        product_category_new = build(:product_category, name: @product_category.name)
        expect(product_category_new.save).to be false
    end
  end
end

The spec runs fine, but when I use before(:all) instead of before(:each), second example fails -
expected false got true I know the difference between before(:all) and before(:each) but I am not able to find the exact reason why second example fails with before(:all)

Upvotes: 2

Views: 872

Answers (1)

eikes
eikes

Reputation: 5061

before :all only runs once before all the examples, so the @product_category is created once. If you have a something like a DatabaseCleaner truncation running after each test, the record is no longer in the database in the second test, thus passing the validation.

before :each on the other hand will be run before each example, so the record will be there in the second example even if the database was cleaned in the meantime.

Upvotes: 4

Related Questions