Home > Back-end >  Is there a way to build multiple models and create relationship between the models and user in RSpec
Is there a way to build multiple models and create relationship between the models and user in RSpec

Time:04-09

I have this method:

  def current_budget(user)
    total = 0
    user.transactions.each do |t|
      if t.income_or_expense
        total  = t.amount
      else
        total -= t.amount
      end
    end
    total
  end

My goal is to write an RSpec test for this method. I want to create multiple transactions and assign them to a user such that when I send that user to this method, the method returns the sum of all transactions.

eg:
Transaction1: amount: 25, user_id: 1
Transaction2: amount: 30, user_id: 1
Transaction3: amount: 35, user_id: 1
user: user_id: 1

it { expect(current_budget(user)).to eq(90) }

User model

class User < ApplicationRecord
  has_many :transactions
end

Transaction model

class Transaction < ApplicationRecord
  belongs_to :user
end

CodePudding user response:

You can build these objects and relate them to each other with any Active Record association method.

In a simple way, you could just build transactions and create a new user with it:


let(:user) { User.create(transactions: transactions) }
let(:transactions) do
  [25, 30, 35].map do |amount|
    Transaction.build(amount: amount)
  end
end

it { expect(current_budget(user)).to eq(90) }

But creating objects one by one could become a pain in the neck. There are some gems that provide a great way to build objects, one of them is factory_bot.

If you define a factory user and transaction, you could just call them like that

let(:user) { create(:user, transactions: transactions) }
let(:transactions) do
  [25, 30, 35].map do |amount|
    build(:transaction, amount: amount)
  end
end

it { expect(current_budget(user)).to eq(90) }
  • Related