Как проверить метод «инициализации» с помощью RSpec - PullRequest
0 голосов
/ 13 февраля 2020

github_asset.rb

# frozen_string_literal: true

require 'asset_ingester/helpers/project_details'
require 'active_model'

module AssetIngester
  module Asset
    class GithubAsset
      include ActiveModel::Serializers::JSON

      attr_reader :id, :name, :full_name, :description, :owner_name, :owner_url,
                  :owner_avatar_url, :url, :html_url, :artifact_id, :jiras, :asset_type

      # Public: Initializes an instance of the GithubAsset class
      #
      # repo        - A hash containing github repository details
      # asset_type  - A string representation of the asset type
      def initialize(repo, asset_type)
        @id = repo[:id]
        @name = repo[:name]
        @full_name = repo[:full_name]
        @description = repo[:description]
        @owner_name = repo.dig(:owner, :login)
        @owner_url = repo.dig(:owner, :url)
        @owner_avatar_url = repo.dig(:owner, :avatar_url)
        @url = repo[:url]
        @html_url = repo[:html_url]
        @asset_type = asset_type
        @artifact_id = repo[:artifact_id] if repo[:artifact_id] && !repo[:artifact_id].empty?
        @jiras = repo[:jiras] if repo[:jiras] && !repo[:jiras].empty?
      end

      # Public: Defines the JSON serialization structure
      #
      # https://edgeguides.rubyonrails.org/active_model_basics.html#serialization
      def attributes
        {
          'id' => @id,
          'name' => @name,
          'full_name' => @full_name,
          'description' => @description,
          'owner_name' => @owner_name,
          'owner_url' => @owner_url,
          'owner_avatar_url' => @owner_avatar_url,
          'url' => @url,
          'html_url' => @html_url,
          'asset_type' => @asset_type,
          'artifact_id' => @artifact_id,
          'jiras' => @jiras
        }.compact
      end
    end
  end
end

github_asset_spe c .rb

require 'asset_ingester/asset/github_asset'

RSpec.describe AssetIngester::Asset::GithubAsset, type: :api do
    context "creating" do 
        let(:asset_type) {"node_package"}
        let(:repo) do
            [id: 131_690,
                name: 'acm-care-management-js',
                full_name: 'AcuteCaseManagementUI/acm-care-management-js',
                owner_name: 'AcuteCaseManagementUI',
                owner_url: 'https://github.cerner.com/api/v3/users/AcuteCaseManagementUI',
                owner_avatar_url: 'https://avatars.github.cerner.com/u/4095?',
                url: 'https://github.cerner.com/api/v3/repos/AcuteCaseManagementUI/acm-care-management-js',
                html_url: 'https://github.cerner.com/AcuteCaseManagementUI/acm-care-management-js',
                asset_type: 'node_package',
                artifact_id: "",
                jiras: [] ]
            end

        describe '::attributes' do
            subject { AssetIngester::Asset::GithubAsset.attributes(repo, asset_type) }

            it 'instantiates the class with 2 arguments' do
              expect(subject).to be_an_instance_of(AssetIngester::Asset::GithubAsset)
            end

            it 'sets a to the first argument' do
              expect(subject.repo).to eq(repo)
            end

            it 'sets b to the second argument' do
              expect(subject.asset_type).to eq(asset_type)
            end
          end
    end
end

Вот как я пытался протестировать файл github_asset.rb, но я получаю следующую ошибку при определении субъекта

AssetIngester :: Asset :: GithubAsset создает :: атрибуты создает экземпляр класса с 2 аргументами Ошибка / Ошибка: субъект {AssetIngester :: Asset :: GithubAsset.attributes (repo, asset_type)} *

 NoMethodError:
   undefined method `attributes' for AssetIngester::Asset::GithubAsset:Class
   Did you mean?  attr_writer

Я тестирую RSpe c, и хочу знать, как это можно сделать.

1 Ответ

0 голосов
/ 13 февраля 2020

Вы получаете это NoMethodError, потому что пытаетесь вызвать attributes как метод класса :

subject { AssetIngester::Asset::GithubAsset.attributes(repo, asset_type) }
#                                           ^^^^^^^^^^

, хотя в вашем коде attributes определяется как метод экземпляра .

Но, кроме этого, вы спрашиваете "как можно протестировать ruby метод инициализации" , и, очевидно, ваш тестовый код полностью равен initialize а не о attributes, поэтому давайте начнем с начала:

describe '::attributes' do
  # ...
end

Вы хотите проверить initialize,, поэтому attributes должно быть initialize. И поскольку initialize является методом экземпляра (а не методом класса), :: должно быть #:

describe '#initialize' do
  # ...
end

И ваш subject должен быть экземпляром GithubAsset, который создан с помощью new 1 :

describe '#initialize' do
  subject { AssetIngester::Asset::GithubAsset.new(repo, asset_type) }

  # ...
end

С этим вы можете начать писать свои тесты, например:

describe '#initialize' do
  subject { AssetIngester::Asset::GithubAsset.new(repo, asset_type) }

  it 'sets the id attribute' do
    expect(subject.id).to eq(131690)
  end
end

1 В Ruby вы редко вызываете ::allocate и #initialize напрямую. Поэтому вместо:

obj = Array.allocate
obj.send(:initialize, 5) { |i| i ** 2 }
obj #=> [0, 1, 4, 9, 16]

вы обычно просто звоните new и позволяете ему звонить allocate и initialize для вас:

obj = Array.new(5) { |i| i ** 2 }
obj #=> [0, 1, 4, 9, 16]
...