简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM