sethi
sethi

Reputation: 1889

Rspec - Model testing with before all to set up model

I am trying something which is very common i think but i am not able to do it because of transactional example.

Here is what i am trying to do

class A < ActiveRecord::Base
  has_many :b
end

class B < ActiveRecord::Base
 belongs_to :a
end

For the testcase

describe A do
  before(:all) do
    @a = Factory.create :a
    @a.b.create()
    # Lot of other things which is common to all example
  end

  it { expect state_one(@a) }
  it { expect state_two(@a)  }
end

What i am trying to do is set up all the precondition for the tests in the before all and have only one expectation per example.The problem is there are no rows in either table A or B in the context of the examples.

Please let me know if it is the correct approach if yes how can i do it?

Upvotes: 0

Views: 190

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

You can have a setup like this:

  describe A do
    subject do
      create(:a).tap do |a|
        create(:b, a: a)
      end
    end

    before(:all) do
      # Lot of other things which is common to all example
    end

    context 'state_one' do
      it { expect state_one(@a) }
    end

    context 'state_two' do
      it { expect state_two(@a)  }
    end
  end

Assuming that you have factories for a and b and setup their association properly.

Upvotes: 1

Related Questions