LoginSignup
44
53

More than 5 years have passed since last update.

Solidusを利用してテストを書くために必要な初期の知識

Posted at

Solidusとは

SolidusはRuby on Rails製のオープンソースECパッケージです。
Solidusを使うとECサイトが爆速で作ることができますが、独自のお作法が多くとっつきにくいです。

下記Qiitaの記事が最初の取っ掛かりとしてはとても参考になりました。
SolidusでECサイトを作る際の方法と考え方

Solidus は責務に閉じたいくつかの gem で一つの機能を実現しています。主に利用する頻度が高そうなのは、
solidus_core (モデル等)
solidus_backend(管理画面等)
solidus_frontend (ECサイト側機能等)です。

本記事では、Solidus内ではじめから準備されているのファクトリやヘルパーを利用したテスト(Rspec)の書き方を紹介します。

Solidusのテストデータがどこにあるのか

EDITOR環境変数が設定済みであれば下記のコマンドで「solidus_core」を開けます。

bundle open solidus_core

solidus_core内にある下記のファクトリに生成データがあります。

solidus_core-2.7.0/lib/spree/testing_support/factories

テストデータを自分のプロジェクトで使うための準備

railsヘルパに下記のように記述します。

rails_helper.rb
require 'spec_helper'
#
#
# 既存のコード
#
# ↓追加
require 'spree/testing_support/factories'
#
#
RSpec.configure do |config|
#
#
# ↓以下を記述しておくといちいちFactryBotを打たなくてよくなる
config.include FactoryBot::Syntax::Methods
#
end

テストデータを使ってみる

controller-specfeature-specなどで以下のようにcreateするとsolidus内のtesting_support/factories で定義されたデータが作られる

example.controller_spec.rb
RSpec.describe "Products_request", type: :request do
  describe "GET #show" do
    let!(:product) { create(:product) }
  end
end

以下がsolidusに実際に記述されているテストデータを生成するためのコードがこちら

testing_support/factories
factory :product do
  tax_category { |r| Spree::TaxCategory.first || r.association(:tax_category) }

  factory :product_in_stock do
    after :create do |product|
    product.master.stock_items.first.adjust_count_on_hand(10)
  end

  factory :product_not_backorderable do
    after :create do |product|
      product.master.stock_items.first.update_column(:backorderable, false)
    end
  end
end

以下が作成されたデータになり、上のcreate(:product)の後ろにname等をつけるとカラムの値を指定することもできる。

例)let!(:product) { create(:product, name: "T-shirts")}

(byebug)<Spree::Product id: 11, name: "Product #5 - 1937", description: "As seen on TV!", available_on: "2017-11-29 02:15:20", deleted_at: nil, slug: "product-5-1
937", meta_description: nil, meta_keywords: nil, tax_category_id: 11, shipping_category_id: 11, created_at: "2018-11-29 02:15:20", updated_at: "2018-11-29

02:15:20", promotionable: true, meta_title: nil>

solidusを使用してテスト(Rspec)を書くには、すでに定義されているモデルやファクトリがどう動くか理解する必要があり
理解するのにかなり時間が取られます。
なのでsolidus_coreのモデルと上のようなfactoryを深く読み解いていき値を設定するようにしましょう。

参考文献

[日本語訳] TESTING SPREE APPLICATIONS

44
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
53