Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec test case in after_save

I have two models Page Article. For every article created a page gets created with the attributes of article. As follows:

class Article

after_save :article_page_create

def article_page_create
    site = Site.find_by(data_proxy_id: self.data_proxy_id)
    page = Page.where(entity_id: self.id)
    if page.blank?
      if article_type == 'StaticPage'
        Page.create(entity_id: self.id, url: "/static/#{self.url_part}", page_type: 'static_page')
      else
        Page.create(entity_id: self.id, url: self.url, page_type: 'article_page')
      end
    else
      return page.update(url: self.url) unless article_type == 'StaticPage'
      page.update(url: "/static/#{self.url_part}")
    end
  end
end

I am trying test cases for the first time. So far this is how far I got.

article_spec.rb

require 'rails_helper'
RSpec.describe Article, type: :model do
  context 'validation tests' do
     it 'ensures article attrs presence' do
        page = Page.create(entity_id: self.id, url: "/static/#{self.url_part}", page_type: 'static_page')
        expect(page).to eq(true)
     end
  end
end

I just wanted know is this the way to test my after_save method. Correct me if I am wrong, please.

like image 772
user3576036 Avatar asked Feb 04 '26 06:02

user3576036


1 Answers

Hmmmm, I think I can help out here.

When testing callbacks, you need to test two assumptions:

Is it being called for the correct event? Is it doing what it's supposed to be doing?

And remember, you want to try make sure your tests cover one specific case.

Your specs should be reading:

On saving an article, I expect the class to receive a callback method

On saving a new article, I expect the number of Page elements to increase by one

On saving an old article, I expect an existing page to be updated

You can continue to flesh out based on the article types etc.

E.g.

it 'triggers a callback to create a page on save' do
  expect(my_class_instance).to receive(:article_page_create)
  @article.save
end

context 'when creating a new page' do
  it "creates a new article" do
    # expect number of pages to change by 1
  end
end

context 'when updating an old page' do
  it 'updates the corresponding article' do 
    # expect attribs to be correct for corresponding page
  end
end
like image 155
Stuart Avatar answered Feb 05 '26 21:02

Stuart