IT박스

Factory Girl에서 배열 / 해시를 정의하는 방법은 무엇입니까?

itboxs 2020. 10. 14. 07:37
반응형

Factory Girl에서 배열 / 해시를 정의하는 방법은 무엇입니까?


중첩 된 해시를 사용하여 배열의 데이터를 반환하는 Dropbox REST 서비스의 일부 반환 값을 시뮬레이션하는 테스트를 작성하려고합니다.

반환 결과가 내부에있는 배열이기 때문에 내 공장을 코딩하는 방법을 알아내는 데 문제가 있습니다. 여기에 무엇이 갈까요?

Factory.define :dropbox_hash do
 ??
end

Dropbox 데이터는 다음과 같습니다.

 ["/home", {"revision"=>48, "rev"=>"30054214dc", "thumb_exists"=>false, "bytes"=>0, "modified"=>"Thu, 29 Dec 2011 01:53:26 +0000", "path"=>"/Home", "is_dir"=>true, "icon"=>"folder_app", "root"=>"app_folder", "size"=>"0 bytes"}] 

그리고 내 RSpec에서 다음과 같은 공장 호출을 원합니다.

Factory.create(:dropbox_hash)

나는 똑같은 일을하는 것에 관심이 있었고, 또한 제 3 자 API의 콘텐츠 해시를 사용하여 작동하는 내 모델을 테스트하는 데 관심이있었습니다. factory_girl의 몇 가지 내장 기능을 사용하여 이러한 종류의 데이터 구조를 깔끔하게 구성 할 수 있음을 발견했습니다.

다음은 인위적인 예입니다.

  factory :chicken, class:Hash do
    name "Sebastian"
    colors ["white", "orange"]

    favorites {{
      "PETC" => "http://www.petc.org"
    }}

    initialize_with { attributes } 
  end

여기서 주요 트릭은 initialize_with를 선언 할 때 factory_girl이 더 이상 결과 객체에 속성을 할당하려고 시도하지 않는다는 것입니다. 이 경우 db 저장소를 건너 뛰는 것 같습니다. 따라서 복잡한 것을 구성하는 대신 이미 준비된 속성 해시를 콘텐츠로 다시 전달합니다. 짜잔.

실제로 사용되지는 않지만 클래스에 대한 일부 값을 지정할 필요가있는 것 같습니다. 이는 factory_girl이 팩토리 이름을 기반으로 클래스를 인스턴스화하려고 시도하는 것을 방지하기위한 것입니다. Object 대신 설명 클래스를 사용하기로 선택했지만 그것은 당신에게 달려 있습니다.

다음 해시 팩토리 중 하나를 사용할 때 여전히 필드를 재정의 할 수 있습니다.

chick = FactoryGirl.build(:chicken, name:"Charles")

.. 그러나 중첩 된 콘텐츠가 있고 더 깊은 필드를 재정의하려면 일종의 깊은 병합을 수행하기 위해 초기화 블록의 복잡성을 증가시켜야합니다.

귀하의 경우 일부 혼합 배열 및 해시 데이터를 사용하고 있으며 데이터 구조의 일부간에 Path 속성을 재사용해야하는 것으로 보입니다. 문제 없습니다. 콘텐츠의 구조를 알고 있으므로 결과 배열을 올바르게 구성하는 팩토리를 쉽게 만들 수 있습니다. 방법은 다음과 같습니다.

  factory :dropbox_hash, class:Array do
    path "/home"
    revision 48
    rev "30054214dc"
    thumb_exists false
    bytes 0
    modified { 3.days.ago }
    is_dir true
    icon "folder_app"
    root "app_folder"
    size "0 bytes"

    initialize_with { [ attributes[:path], attributes ] }
  end

  FactoryGirl.build(:dropbox_hash, path:"/Chickens", is_dir:false)

또한 여전히 불필요한 값을 생략 할 수 있습니다. Path와 rev 만 실제로 필요하다고 상상해 봅시다.

  factory :dropbox_hash, class:Array do
    path "/home"
    rev "30054214dc"
    initialize_with { [ attributes[:path], attributes ] }
  end

  FactoryGirl.build(:dropbox_hash, path:"/Chickens", revision:99, modified:Time.now)

나를 위해 작동하고 필요에 따라 속성을 해시에 전달할 수 있습니다.

factory :some_name, class:Hash do
  defaults = {
    foo: "bar",
    baz: "baff"
  }
  initialize_with{ defaults.merge(attributes) }
end

> build :some_name, foo: "foobar" #will give you
> { foo: "foobar", baz: "baff" }

현재 RSpec 버전 (3.0)에 대한 후속 조치 :

평상시처럼 공장을 정의 FactoryBot.attributes_for하고 인스턴스화 된 클래스 대신 해시를받는 데 사용하십시오 .


최신 버전의 factory_girl에서이 작업을 수행 할 수 있지만 데이터 구조가 아닌 객체를 빌드하도록 설계 되었기 때문에 어색합니다. 예를 들면 다음과 같습니다.

FactoryGirl.define do
  factory :dropbox_hash, :class => 'Object' do
    ignore do
      url { "/home" }
      revision { 48 }
      rev { "30054214dc" }
      # more attributes
    end
    initialize_with { [url, { "revision" => revision, "rev" => rev, ... }] }
    to_create {}
  end
end

Going over the weird stuff here:

  • Every factory needs a valid build class even if it's not used, so I passed Object here to prevent it from looking for DropboxHash.
  • You need to ignore all the attributes using an ignore block so that it doesn't try to assign them to the array afterwards, like array.revision = 48.
  • You can tell it how to put your result together using initialize_with. The downside here is that you need to write out the full attribute list again.
  • You need to provide an empty to_create block so that it doesn't try to call array.save! afterwards.

I used OpenStruct:

factory :factory_hash, class:OpenStruct do
  foo "bar"
  si "flar"
end

Edit: sorry, does not work as an Hash

I finally use a static version, just to keep that hash coming from the Factory system...

factory :factory_hash, class:Hash do
  initialize_with { {
    foo "bar"
    si "flar"
  } }
end

looking for something better

참고URL : https://stackoverflow.com/questions/10032760/how-to-define-an-array-hash-in-factory-girl

반응형