user3576036
user3576036

Reputation: 1435

Rspec test for model create

This is my first time writing a test case. I have model where I am doing a callback to create an object for another model.

class Model1
 after_save :create_model2_object

 def create_model2_object
  Model2.create(id: self.id, name: self.name) 
 end
end

The test case I wrote is as follows:

model1_spec.rb

require 'rails_helper'
RSpec.describe Model1, type: :model do
  context 'validation tests' do
     it 'ensures article attrs presence' do
        page = Model2.create(entity: self.id, name: self.name)
        expect(page).to eq(true)
     end
  end
end

When I run this both the development and test data goes empty. I know I am doing something completely wrong. Could somebody please help me here?

Upvotes: 1

Views: 4336

Answers (1)

Kaushlendra Tomar
Kaushlendra Tomar

Reputation: 1440

You can try this:

require 'rails_helper'
RSpec.describe Model1, type: :model do
  context 'validation tests' do
     it 'ensures article attrs presence' do 
         expect{Model1.create(entity: "entity_id", name: 'name')}.to change{Model2.count}.by(1)
     end
  end
end

Upvotes: 2

Related Questions