Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

任意の子コンポーネントを入れ子にしてテストする | Vuex + vue-test-utils その0003

参考にさせて頂いたページ

はじめに

テスト対象のコンポーネント内部に子コンポーネントを配置していて、shallowMount()の引数として特に設定を追加していない場合は、本来自分が配置しているコンポーネントではなくstubコンポーネントが自動的に挿入されます。

実際の挙動をテストしたいときに、任意のコンポーネントを配置する方法について書きます。

サンプルコード

公式ドキュメントの「マウンティングオプション | Vue Test Utils」のstubsを使用します。

import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
// modules
import myComponentModule from '@/javascripts/my_component_module.js'

// components
import MyComponent from '@/javascripts/my_component.vue';
import MyChildComponent from '@/javascripts/my_child_component.vue';

const localVue = createLocalVue();
localVue.use(Vuex);

describe('my_component.vueのテスト', () => {
  let $store;
  let wrapper;

  beforeEach(() => {
    // 本来のthis.$storeに入るものと同様のオブジェクト構造を作成
    $store = new Vuex.Store({
      state: {},
      getters: {},
      mutations: {},
      actions: {},
      modules: {
        myComponentModule,
      },
    });

    wrapper = shallowMount(MyComponent, {
      mocks: {
        // 本来rootコンポーネントに設定するthis.$storeを使えるように設定
        $store,
      },
      stubs: {
        // ここに子コンポーネントを渡す
        MyChildComponent,
      },
      propsData: {
        // 〜略〜
      },
    });
  });

  it('テストタイトル', () => {
    // 何かテスト
  });
});

this.$storeを参照している子コンポーネントを単体でテストする | Vuex + vue-test-utils その0002

参考にさせて頂いたページ

はじめに

コンポーネント単体でテストをしたいけど、this.$storeを参照しているcomputedなどがあり、テスト実行時にエラーが出たのでどうにかしたかったという経緯があります。

サンプルコード

公式ドキュメントの「マウンティングオプション | Vue Test Utils」にある通り、mocksを使います。

import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
// modules
import myComponentModule from '@/javascripts/my_component_module.js'

// components
import MyComponent from '@/javascripts/my_component.vue';

const localVue = createLocalVue();
localVue.use(Vuex);

describe('my_component.vueのテスト', () => {
  let $store;
  let wrapper;

  beforeEach(() => {
    // 本来のthis.$storeに入るものと同様のオブジェクト構造を作成
    $store = new Vuex.Store({
      state: {},
      getters: {},
      mutations: {},
      actions: {},
      modules: {
        myComponentModule,
      },
    });

    wrapper = shallowMount(MyComponent, {
      mocks: {
        // 本来rootコンポーネントに設定するthis.$storeを使えるように設定
        $store,
      },
      propsData: {
        // 〜略〜
      },
    });
  });

  it('テストタイトル', () => {
    // 何かテスト
  });
});

computedでglobal変数をreturnしているvmをvue-test-utilsでtestする | Vuex + vue-test-utils その0001

参考にさせて頂いたページ

要約すると

要約すると「任意のcomputedを上書きしてからtestを実行する。」ということになります。

例えばプロダクトのコードで、 window.gon = { hoge: 'example_value' } を用意して、これをcomputedのhogeでreturnしている状態があるとします。

例えば以下のようなVueModelです。

window.gon = { hoge: 'example_value' }

const vm = new Vue({
  〜略〜
  computed: {
    hoge () {
      return window.gon.hoge;
    },
  },
  〜略〜
});

上記のようなコンポーネントをテストするとき以下のように記述することで確認できそうです。

  it('テストのタイトル', () => {
    const gon = {hoge: 'example_value'};
    const wrapper = shallowMount(TextField, {
      computed: {
        hoge() {
          return gon.hoge;
        },
      },
    });

    // ここでテストする
    console.log('============================');
    console.log(wrapper.vm.hoge);
    console.log('============================');
  });

環境構築 | Ubuntu18.04 + docker-composeでrailsアプリケーション開発 その0001

参考にさせて頂いたページ

docker-composeのインストール

docker daemonの起動とか

dockerコマンドをsudo無しで実行する方法

docker-compose を使ってrailsの開発環境を構築する

はじめに

途中で躓きすぎてどの辺が上手くいったのかよくわからないです。

ホスト環境

dockerをインストールしてhello worldをやってみる

sudo無しでdockerコマンドを実行できるようにする

以下のリンクは2つありますが、手順をひとつ試して上手くいかない場合には端末を再起動してみてから、もう一つの方法を試すといいかもしれません。

docker-compose をインストールする

公式ドキュメント通りやってみて上手くいかなかったら個人の記事に頼ります。

docker daemonの起動とか

docker daemonの起動とか、自動で起動する方法とかもここで押さえておくと良さそうです。

railsの環境構築をする

だいたい以下のページを参考にさせて頂きました。

ディレクトリを作成して移動

mkdir project
cd project

docker-compose.ymlを作成

自分は version: '2' にしないとエラーが出ましたのでそこだけ変更しています。

自分のdocker-compose ymlの内容は下記の通りです。

version: '2'

services:
  web:
    build: .
    ports:
      - "3000:3000"
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
      - bundle:/usr/local/bundle
    depends_on:
      - db
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: password
    # MYSQL_ALLOW_EMPTY_PASSWORD: "yes"  パスワードなしにしたい場合はこれ
    ports:
      - '3306:3306'
    volumes:
      - mysql_data:/var/lib/mysql
volumes:
  bundle:
  mysql_data:

Dockerfileを作成

rubyバージョンだけ新しいものにしていますが、それ以外はそのままです。

FROM ruby:2.6.3
ENV LANG C.UTF-8

RUN apt-get update -qq && apt-get install -y \
    build-essential \
    nodejs \
 && rm -rf /var/lib/apt/lists/*

RUN gem install bundler

WORKDIR /tmp
ADD Gemfile Gemfile
ADD Gemfile.lock Gemfile.lock
RUN bundle install

ENV APP_HOME /myapp
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME
ADD . $APP_HOME

Gemfileを作成

Gemfileはそのままです。railsのバージョンも新しい方が良いかもしれませんが。

source 'https://rubygems.org'

gem 'rails', '5.1.4'

Gemfile.lockを作成

空のファイルを作成します。

以下のコマンドで作成しました。

touch Gemfile.lock

コマンド実行

参考ページにならってwebサービスrails newします。

docker-compose run --rm web bundle exec rails new . --force --database=mysql --skip-bundle

docker-compose buildします。

docker-compose build

webサービスにbundle installしてgemをインストールします。

docker-compose run --rm web bundle install

docker-compose upします。

docker-compose up

以下の表示で止まりました。

db_1  | Version: '5.7.26'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)

ブラウザでアクセスしてみる

http://localhost:3000/ にブラウザでアクセスしたらrailsの初期ページが表示されました。

一度止める

別タブでprojectディレクトリまで移動して、以下のコマンドで止まります。

docker-compose down

ディレクトリとファイルの所有者変更

このままだとrails newによって生成されたファイルの所有者がrootなので、以下のような感じで所有者を変更すると編集しやすいと思います。

.gitディレクトリを削除

projectディレクトリに.gitディレクトリが作成されているので削除すると良いと思います。

任意のgitリポジトリで管理する

projectディレクトリを丸ごと任意のgitリポジトリにコミットすると楽だと思います。

今後サーバーを起動するとき

以下のように-dを付けてバックグラウンドで起動するのも良いと思います。

docker-compose up -d

| Ubuntu18.04 + dockerのCentOSイメージでrails その0001

はじめに

全くまとまってい ない自分用メモです。

この手順通りやっても動くかどうかもわかりません。

そのうち暇なときにまとめ直そうと思います。

dockerのインストールとHelloWorld

まず以下の記事の手順でHelloWorldまでやりました。

ubuntu18.04でdockerのHelloWorldまでやってみる - Motomichi Works Blog

centos:7イメージからコンテナを作る

だいたい「vagrantその0029 Windows10 Home + Vagrant + centos-7.3.boxで作った環境にdockerをインストールする - Motomichi Works Blog」のような感じですが、コンテナを作成するときに「dockerのCentOS7.3コンテナでFailed to get D-Bus connection: Operation not permittedになる問題を解決する - Motomichi Works Blog」をしないとpostgresqlのインストールができませんでした。

postgresqlを使う設定でrails newするところまでやる

Dockerfileをもとにimageを生成

sudo docker build -t motomichi/rails ./

コンテナを作成しつつ起動

Failed to get D-Bus connection: Operation not permittedのエラーにならないために--privileged/sbin/initのところがポイント。

mkdir project
cd project
sudo docker run --privileged -i -d -p 8080:3000 -v "${PWD}:/work/project" --name 'rails_tutorial_20180929' motomichi/rails /sbin/init

コンテナに入る

sudo docker exec -it rails_tutorial_20190201 /bin/bash

vimをインストール

# yum install -y vim

sudoをインストール

yum -y install sudo

postgresqlをインストール

リポジトリを追加します。

# yum install -y https://yum.postgresql.org/9.6/redhat/rhel-7-x86_64/pgdg-redhat96-9.6-3.noarch.rpm

postgresql96-server postgresql96-contrib postgresql96-develをインストールします

# yum install -y postgresql96-server postgresql96-contrib postgresql96-devel

psqlコマンドが使えるか確認します。

# psql --version

postgresqlの初期化と起動

初期化します。

# /usr/pgsql-9.6/bin/postgresql96-setup initdb

起動します。

# systemctl start postgresql-9.6.service

OS起動時にpostgresqlが自動で起動するようにします。

# systemctl enable postgresql-9.6.service

CentOS7のコンテナ内にexample_userユーザーを追加しておく

CentOSのコンテナ内にexample_userという名前のユーザーを追加して、パスワードを設定します。

# adduser example_user
# passwd example_user

パスワード: ex_pass

一度rootユーザーからexample_userに切り替えてみます。

# su - example_user

一度rootユーザーに戻します。

$ exit

postgresqlのroleを設定する

https://qiita.com/torini/items/9952d91c4a7087b23481 を参考に進めます。

PostgreSQLのroot userであるpostgresユーザとしてpsqlを実行する

# su - postgres
$ psql

createdbできるroleをexample_userというユーザー名で作成します。

postgres=# create role example_user with createdb login password 'pg_pass';
postgres=# \q

rootに戻ります。

-bash-4.2$ exit

postgresを使う設定でrails newする

example_userに切り替えます。

# su - example_user

移動します。

$ cd /work/project/

postgresqlを使う設定でrails newします。

$ rails new project_1 -d postgresql

自動的にbundle installしたときにErrorが出た様子。

         run  bundle install
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/.........
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Fetching rake 12.3.2
Errno::EACCES: Permission denied @ rb_file_s_rename - (/home/example_user/.gem/ruby/2.5.0/cache/rake-12.3.2.gem,
/usr/local/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/cache/rake-12.3.2.gem)
An error occurred while installing rake (12.3.2), and Bundler cannot continue.
Make sure that `gem install rake -v '12.3.2' --source 'https://rubygems.org/'` succeeds before bundling.

ここで以下の手順を実行します。(※ここで yum install -y sudo をして visudo してusermod -aG wheel sampleuserしました。)

CentOSでuserをsudo可能にする - Qiita

もう一度

$ cd /work/project/project_1
$ bundle install

パスワードを何回か聞かれつつ、example_userのruby gemsにgemが追加されていきます。

gem pgのインストール部分でエラーが出たので解消する

以下のエラーが出ました。

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /tmp/bundler20190201-988-tslah6pg-1.1.4/extensions/x86_64-linux/2.5.0-static/pg-1.1.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20190201-988-tslah6pg-1.1.4/gems/pg-1.1.4 for inspection.
Results logged to /tmp/bundler20190201-988-tslah6pg-1.1.4/extensions/x86_64-linux/2.5.0-static/pg-1.1.4/gem_make.out

An error occurred while installing pg (1.1.4), and Bundler cannot continue.
Make sure that `gem install pg -v '1.1.4' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  pg
         run  bundle exec spring binstub --all
bundler: command not found: spring
Install missing gem executables with `bundle install`

単体でインストールしてみます。

$ gem install pg

以下のエラーが出ました。

Fetching: pg-1.1.4.gem (100%)
ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /usr/local/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0 directory.

このディレクトリはrootの権限でないと駄目そうなのでrootでgem install pgしてみます。

$ exit
# gem install pg

以下のエラーが出ました。

[root@48219310fa38 project]# gem install pg
Building native extensions. This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

    current directory: /usr/local/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/pg-1.1.4/ext
/usr/local/rbenv/versions/2.5.1/bin/ruby -r ./siteconf20190131-3636-1ac726.rb extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/local/rbenv/versions/2.5.1/bin/$(RUBY_BASE_NAME)
    --with-pg
    --without-pg
    --enable-windows-cross
    --disable-windows-cross
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /usr/local/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/extensions/x86_64-linux/2.5.0-static/pg-1.1.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /usr/local/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/pg-1.1.4 for inspection.
Results logged to /usr/local/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/extensions/x86_64-linux/2.5.0-static/pg-1.1.4/gem_make.out

pg_configが見つからないということで、pathを指定してみるといいらしい。

# gem install pg -v '1.1.4' -- --with-pg-config=/usr/pgsql-9.6/bin/pg_config

もう一度example_userに切り替え

# su - example_user

移動します。

$ cd /work/project/project_1/

Gemfileに追記しないとrails sしたときにエラーが出てしまうので追記します。
gem 'mini_racer', platforms: :rubyの下あたりに追記します。
このあたりはrailsのバージョンによって何を書くか、消すかなど微妙に違います。

gem 'therubyracer', platforms: :ruby

bundle installします。

$ bundle install

rails sします。

$ rails s

config/database.ymlに追記します。

  # 以下の4つを追記
  username: example_user
  password: pg_pass

  # RailsサーバとPostgreSQLサーバが同じ場合
  host: localhost
  template: template0

rootユーザーに切り替えてpg_hba.confを編集します。

$ exit
# vim /var/lib/pgsql/9.6/data/pg_hba.conf

IPv4のところを以下のようにmd5に編集しました。

# IPv4 local connections:
#host    all             all             127.0.0.1/32            ident
host    all             all             127.0.0.1/32            md5

設定を反映するためにpostgresを再起動します。

# systemctl restart postgresql-9.6.service

example_userに切り替えて rails db:createします。

# su - example_user
$ cd /work/project/project_1
$ rails db:create
$ rails s

http://localhost:8080/ をブラウザで確認するとrailsのスタートページが表示されました。

Vue.jsでもデザインと振る舞いを分ける(Presentational ComponentとContainer Component について)

参考にさせて頂いたページ

Vue Loader公式

色々

Presentational ComponentとContainer Component について

所感

.vueファイルを以下の3つに分離すると再利用性が高まる

  • HTML文書構造(Template)
  • スタイル(Style)
  • 振る舞い(Script)

具体的には以下のようにsrcを指定すると良さそう。

SFC Spec | Vue Loader

node-sassでディレクトリごとwatch(監視)する

node-sassでディレクトリごとwatch(監視)する

例えば以下のような感じです。

$ node-sass src/entry_points/ -o public/stylesheets/ -w

一応解説すると以下の通りです。-wwatchです。

$ node-sass [監視したいディレクトリ] -o [書き出したいディレクトリ] -w