Startouf
7/23/2017 - 1:55 PM

Refactor jsonapi-suite sideposting into shared examples for RSpec

Refactor jsonapi-suite sideposting into shared examples for RSpec

# spec/requests/api/create_post_spec.rb
require 'rails_helper'
require 'requests/api/concerns/commentable_sidepost_spec.rb'

describe API::V1::PostsController, type: :request do
  let(:user) { create(:user) }
  let(:author) { user }
  let(:post_attributes) do {
    title: Faker::Lorem::Sentence.new,
    author_id: author.id.to_s
  } end
  
  describe '#create' do
    let(:payload) do {
      data: {
        type: 'post',
        attributes: post_attributes,
        relationships: relationships,
        included: included_data
      }
    } end
    let(:relationships) { {} }
    let(:included_data) { {} }

    context 'signed in as a user' do
      let(:auth_headers) { json_token_auth_headers_for(user) }

      it_should_behave_like('a commentable object') do
        let(:commentable) { Post.first }
        let(:request) { create_request }
      end
    end
  end

  def create_request
    post api_v1_posts_path, params: payload, headers: auth_headers
  end
end



# /requests/api/concerns/commentable_sidepost_spec.rb
require 'spec_helper'

shared_examples_for 'an commentable object' do
  context 'with 2 comments' do
    let(:comments) { FactoryGirl.build_list(:comment, 2)}

    let(:relationships) do {
      comments: {
        data: comments.map.with_index do |tag, i|
          {
            type: 'comment',
            'temp-id': i,
            method: 'create'
          }
        end
      }
    } end

    let(:included_data) do
      comments.map.with_index do |com, i|
        {
          type: 'comment',
          'temp-id': i,
          attributes: com.as_json(only: [:title, :description])
        }
      end
    end

    it 'creates comments via sidepost' do
      create_request
      comments_in_db = commentable.reload.comments
      expect(comments_in_db.map(&:title)).to eq(comments.map(&:title))
      expect(comments_in_db.map(&:description)).to eq(comments.map(&:description))
    end
  end
end