nmcli 使い方

いつも忘れるので個人の防備録用、(でも設定ファイルの方がやりやすいのになー。特にKVMでクローンしたサブホストは固定のIPアドレスやホスト名がダブっているので、ログインしないと変更出来ない。設定ファイルならlosetupやkaprtxを使い簡単に変更出来るのに)
ブリッジの追加
# nmcli con add type bridge ifname br0 con-name br0
(ethernet の時:# nmcli c add type ethernet ifname enp10s0 con-name enp10s0)
# nmcli con mod br0 bridge.stp no
固定IPにし、アドレス設定
# nmcli con mod br0 ipv4.method manual ipv4.address 192.168.xx.xx/24
ipv4.gateway 192.168.xx.xx ipv4.dns 168.168.xx.xx +ipv4.dns 8.8.8.8
インターフェイスを割り当てる。インターフェースはenp2s0、ブリッジはbridge-br0の時
# nmcli con add type bridge-slave  ifname enp2s0 master br0
いらないenp2s0を削除
# nmcli con del enp2s0
で、rebootし設定の反映。
インターフェースの固定IPなどを変更した場合等はリブートせず、
# nmcli con up デバイス名(enp2s0など)
で反映させられる

リソースを変更する時(例:VIPcheck)
# nmcli resource update VIPcheck IPaddr2 ip=192.168.xx.xx

connection名を変更する時
変更前
# nmcli con show
NAME                 UUID                                                  TYPE         DEVICE
enp1s0   301d8125-15e4-30a7-9a51-f3b6044f9f86  ethernet   enp1s0
enp11s0 659ee2d1-e1e4-4e6a-a212-733fe8b984d8 ethernet  enp12s0
lo            c14f53f1-e355-4075-8ed7-53c1ae1844e0   loopback lo
# nmcli con mod enp11s0 connection.id enp12s0
# nmcli con up enp12s0
# nmcli con show
NAME                 UUID                                                  TYPE         DEVICE
enp1s0    301d8125-15e4-30a7-9a51-f3b6044f9f86  ethernet   enp1s0
enp12s0 659ee2d1-e1e4-4e6a-a212-733fe8b984d8 ethernet   enp12s0
lo             c14f53f1-e355-4075-8ed7-53c1ae1844e0   loopback lo
でめでたくconnection名(NAME)がenp12s0になった

カテゴリー: Linux運用時のメモ | コメントする

ダブっている写真を消去する(linux)

ある時ファイルサーバーのファイルを見ると大量の複製している画像や動画があった。
これを消去しようとスクリプトを組もうとして調べるともっと簡単に出来ることが判った。
ダブっている画像や動画は*(1).JPG や*(1).MOVなので cd でそのdirectory にいって
# find -iname *(1).JPG
# find -iname *(1).MOV
で綺麗にダブっている分が消去された。因みに -iname はファイル名の指定で大文字と小文字をチェックしない指定

カテゴリー: Linux運用時のメモ | コメントする

rsyncのexclud-fromでの指定の色々

rsyncでexclude-fromファイルの中でexcludeしたいファイルの指定方法であまり正規化表現が指定できないので色々迷っていたが、https://futuremix.org/2011/02/rsyncが参考になった。ポイントは

-C(または–cvs-exclude) オプションを使うと CVS などバージョン管理システムの生成するファイルなどを自動的に除外してくれます。
これは CVS だけではなく、Subversion や .bak .exe などの拡張子を持つファイルも除外されます。具体的には
*~ #* .#* ,* _$* *$ *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb *.o
*.obj *.so *.exe *.Z *.elc *.ln core .svn/

正規表現はあまり使えませんが、[0-9] のような数値指定は可能です。
また * と ** も使用できます。** はディレクトリ区切りを超えてマッチします。この意味は **/.recycle/* とすると aaa/.recycle/* とも aaa/bbb/ccc/.recycle/* ともマッチするとのこと

なので私のexcludeファイルは(sambaのバックアップを取る時の指定)

/.Trash-0/
/lost+found/
/*/.recycle/
/**/cache/
/**/$RECYCLE.BIN/*

とした。

カテゴリー: Linux運用時のメモ | コメントする

NVMeをddでコピーしたらエラー

ルート領域に使っているNMVeを大きい容量のNMVeにddでコピーしたら下記のエラーが出た(注:ddでdisk毎コピーすると容量がオリジナルの容量になるが、以前はgpartedで容量を増やしていたが、今はpartedで、diskを見ると(p)容量がおかしいので、FIXするか聞いてくるので、fixと入れると本来のサイズにアップしてくれる)
# lvs -a -o +devices
WARNING: Couldn’t find device with uuid DMr0bx-8hT0-qAr0-Can8-IcVq-F4Zr-or5v0h.
WARNING: VG Data5 is missing PV DMr0bx-8hT0-qAr0-Can8-IcVq-F4Zr-or5v0h (last written to /dev/nvme0n1p6).
WARNING: Couldn’t find device with uuid ydBOpY-3v1F-l5KD-Hj73-C1Yw-LPoC-425E9H.
WARNING: VG SubHost5 is missing PV ydBOpY-3v1F-l5KD-Hj73-C1Yw-LPoC-425E9H (last written to [unknown]).
LV   VG   Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert Devices
Backup Backup -wi——- 1.46t /dev/sdb6(0)
Download Data5 -wi——- 50.00g /dev/sda6(0)
以下省略
前にSSDで同じ事をしてもエラーにならなかったが、NVMeだからエラーになるの??
(注:/etc/lvm/lvm.confにある# use_devicesfile = 1はコメントを取り、use_devicesfile = 0でエラーが出ないようにしている)
なので、
# pvcreate –help  すると
前略
pvcreate PV …
  [ -f|–force ]
  [ -M|–metadatatype lvm2 ]
  [ -u|–uuid String ]
  [ -Z|–zero y|n ]
  [   –dataalignment Size[k|UNIT] ]
  [ –dataalignmentoffset Size[k|UNIT] ]
  [ –bootloaderareasize Size[m|UNIT] ]
  [ –labelsector Number ]
  [ –pvmetadatacopies 0|1|2 ]
  [ –metadatasize Size[m|UNIT] ]
  [ –metadataignore y|n ]
  [ –norestorefile ]
以下省略
pvcreate時にUUIDを指定できる見たいなので
# pvcreate -u ydBOpY-3v1F-l5KD-Hj73-C1Yw-LPoC-425E9H –norestorefile /dev/nvme0n1p6
Physical volume “/dev/nvme0n1p6” successfully created.
となったので
#
pvscan
PV /dev/sdb6 VG Backup lvm2 [<1.67 TiB / <207.73 GiB free]
PV /dev/sda6 VG Data5 lvm2 [<200.00 GiB / <10.00 GiB free]
以下省略
と無事エラーを消す事ができた。又、どう言う訳かlast written to [unknown]になっていたVG SubHost5も消えていた。
# lvscan
inactive ‘/dev/Backup/Backup’ [1.46 TiB] inherit
inactive ‘/dev/Data5/Mysql’ [5.00 GiB] inherit
以下省略
と全部inactiveになっていたので、
# vgchange -ay
をすると、LVが全部activeになった。
VG Data5 VG SubHost5 にあったファイルは要らないので問題ない
もし、必要なら、オリジナルのNVMeをUSBでアタッチし、ファイルをコピればいい

カテゴリー: Linux運用時のメモ | コメントする

またまた危険なメール

上の画像の①は差出人だが、今回は偽装されているので、amazon.co.jpから発信されて無い。②は本文の”ご注文の確認”にマウスを持って来ると表示される物だが、クリックするとここに飛ぶ。https://cxqxqxcg.shop/省略、cxqxqxcg.shopに飛ぶ、もちろんここはアマゾンじゃ無いので、絶対にクリックしてはいけない。
詳しくは触れないが、ヘッダーと呼ばれている部分を調べると、IPが183.253.225.254から117.18.0.204に送られ、そこから私に来ているが最初のIPは中国からで二番目は香港になっていた。

カテゴリー: 危険メールや手紙、IP | コメントする

複数のWEBサーバーの全てのリンクが突然切れた。

私はアパッチのバーチャルで複数のWEBを運営していますが、全てのWEBでどのメニューをクリックしても、URLは正しく表示されているが、表示されているページはホームぺージだ!!!
実はDRBDを使い2つのサーバーでプライマリーとセカンダリーを自動で切り替えている。そこで、セカンダリー側をプライマリーにしても同じ状態!!
原因は全く不明なのでがここで何が問題か考える。先ずはアパッチ, phpやデーターベースなどのサーバー側の問題。だけどこれは2台同時にいかれるのは考えにくい。そして各WEBのデーターはデフォルトからは変更をしていて、50GiBの領域を専用に割り当てている。これはDRBDが自動で同期するので、何かの問題でプライマリー側のデーターが問題になると、セカンダリーも同じデーターになる筈。なのでこれが原因と勘繰る。幸いbaculaで バックアップがあるので、仮にアタッチしたディスクにバックアップしている全てのWEBデーターをリストアする。そしてDRBDで動いているWEBサーバーで drbdadm down r0でdrbdをストップしておく。ここでリストアのデーターがある場所が/testと仮定し、WEBデータがある場所を/test2と仮定しコピーをする。
# cd /test
# cp -pr -f ./ /test2
アレー、上書きの確認が出る。このままでは何千回も確認が出るので止める。
これはエイリアスでalias cp=’cp -i’となっているからだ。なのでエイリアスを無効にする。これにはコマンドの前に\(バックスラッシュ)をつければいい。
# \cp -pr -f ./ /test2
やっとコピーが終わり、drbdを起動
# drbdadm up r0
Device ‘0’ is configured!
Command ‘drbdmeta 0 v08 /dev/vdc internal apply-al’ terminated with exit code 20
Device ‘1’ is configured!
Command ‘drbdmeta 1 v08 /dev/vdd internal apply-al’ terminated with exit code 20
とエラーが出る。
念の為、
# pcs status
Online: [ web3 ]      (抜粋)
OFFLINE: [ web4 ]

Full list of resources:

Resource Group: apachegroup
   vipcheck_res (ocf::myres:VIPcheck):       Started web3
   VirtualIP (ocf::heartbeat:IPaddr2):          Started web3
   FS_DRBD0 (ocf::heartbeat:Filesystem):   Started web3
   FS_DRBD1 (ocf::heartbeat:Filesystem):   Started web3
   HTTPD (ocf::heartbeat:apache):              Started web3
   MARIADB (systemd:mariadb):     Started web3
   POSTFIX (systemd:postfix):         Started web3
   dovecot (systemd:dovecot):         Started web3
Master/Slave Set: MS_DRBD0 [DRBD0]
   Masters: [ web3 ]
   Stopped: [ web4 ]

Failed Resource Actions:
* DRBD0_monitor_20000 on web3 ‘not running’ (7): call=40, status=complete, exitreason=”,
    last-rc-change=’Wed Sep 13 12:01:41 2023′, queued=0ms, exec=0ms
あれー、エラーは出ているもののdrbdも起動している。

このエラーはそのままにして、もう片方のサーバーを立ち上げて
# pcs status
とすると(抜粋)
Online: [ web3 web4 ]

Full list of resources:

Resource Group: apachegroup
   vipcheck_res (ocf::myres:VIPcheck):       Started web3
   VirtualIP (ocf::heartbeat:IPaddr2):          Started web3
   FS_DRBD0 (ocf::heartbeat:Filesystem):   Started web3
   FS_DRBD1 (ocf::heartbeat:Filesystem):   Started web3
   HTTPD (ocf::heartbeat:apache):              Started web3
   MARIADB (systemd:mariadb):         Started web3
   POSTFIX (systemd:postfix):             Started web3
   dovecot (systemd:dovecot):             Started web3
Master/Slave Set: MS_DRBD0 [DRBD0]
   Masters: [ web3 ]
   Slaves: [ web4 ]

Failed Resource Actions:
* DRBD0_monitor_20000 on web3 ‘not running’ (7): call=40, status=complete, exitreason=”,
     last-rc-change=’Wed Sep 13 12:01:41 2023′, queued=0ms, exec=0ms

Daemon Status:
    corosync: active/enabled
   pacemaker: active/enabled
   pcsd: active/enabled

エラーが出ているものの、初めに立ち上げたWEBが動いているようなので、WEBにアクセスすると無事元に戻っていた。
# cat /proc/drbd
0: cs:Connected ro:Secondary/Primary ds:Diskless/UpToDate C r—–
ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:b oos:0
1: cs:Connected ro:Secondary/Primary ds:Diskless/UpToDate C r—–
ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:b oos:0
disklessになっているので
# drbdadm attach r0
0: cs:Connected ro:Secondary/Primary ds:Negotiating/UpToDate C r—d-
ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:12264
1: cs:Connected ro:Secondary/Primary ds:Negotiating/UpToDate C r—d-
ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:120
何時迄もNegotiatingのままなので、drbdを再起動してみる
# systemctl restart drbd
# cat /proc/drbd
0: cs:StandAlone ro:Secondary/Unknown ds:UpToDate/DUnknown r—–
ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:12264
1: cs:StandAlone ro:Secondary/Unknown ds:UpToDate/DUnknown r—–
ns:0 nr:0 dw:0 dr:0 al:0 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:120
これでスプリットブレイン状態になったので、
# drbdadm — –discard-my-data connect r0

そして最初に起動したサーバーに戻って
出て行たエラーを消す
# pcs resource cleanup
そしてスプリットブレインを解消するため
# drbdadm connect r0
でもってcat /proc/drbdで見ると動機が始まった。

これでやっと正常になった。

カテゴリー: Linux運用時のメモ | コメントする

7:チュートリアルの4章以降

4章からは有料のRailsチュートリアルのコンテンツ閲覧アカウント登録がいりますので、書きませんが、途中気が付いた事を書きます。
html.erbのコメントの書き方(rubyのコメント)
 1:<%# コメントアウト %>
 2:<%= begin %>コメントアウト<%= end %>
 3:<% if false %>コメントアウト<% end %>
ダブルクォートとシングルクォート
 どちらも同じ文字列を表すが、シングルクォート文字列の中では式展開を行いません。

カテゴリー: Ruby on railsに挑戦(almalinux9), その他 | コメントする

6:少しだけ動的なページ

ページの内容に応じて、ページのタイトルを自ら書き換えて表示するようにします。レイアウトもデフォルトで作成されますがコピーを取っておきます
$ mv app/views/layouts/application.html.erb layout_file
StaticPagesコントローラのタイトルをテストするが、コントローラーを変更する
$ gedit test/controllers/static_pages_controller_test.rb
require “test_helper”
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test “should get home” do
    get static_pages_home_url
    assert_response :success
    assert_select “title”, “Home | Ruby on Rails Tutorial Sample App” ←追記
end
  test “should get help” do
    get static_pages_help_url
    assert_response :success
    assert_select “title”, “Help | Ruby on Rails Tutorial Sample App” ←追記
end

 test “should get about” do
    get static_pages_about_url
    assert_response :success
    assert_select “title”, “About | Ruby on Rails Tutorial Sample App” ←追記   end
end
テストする
$ rails test
前略
3) Failure: StaticPagesControllerTest#test_should_get_help [/Rails/environment/sample_app/test/controllers/static_pages_controller_test.rb:13]: Expected at least 1 element matching “title”, found 0. Expected 0 to be >= 1. 3 runs, 6 assertions, 3 failures, 0 errors, 0 skips
3つfaileresが出ている。エラーに’Expected at least 1 element matching “title”, found 0’と出ている。viewにtitleが無いと言っているので
$ gedit app/views/static_pages/home.html.erb
<!DOCTYPE html>  ←ここから
<html>
  <head>
    <title>Home | Ruby on Rails Tutorial Sample App</title>
  </head>
  <body>    ←ここまで追記
    <h1>Sample App</h1>
    <p>
      This is the home page for the
      <a href=”https://railstutorial.jp/”>Ruby on Rails Tutorial</a>
      sample application.
    </p>
  </body>    ←ここから
</html>     ←ここまで追記
元から有ったものには見やすくするためにインテンドが入っている 同様にhelpとaboutも作る app/views/static_pages/help.html.erbの内容
<!DOCTYPE html>
<html>
  <head>
    <title>Help | Ruby on Rails Tutorial Sample App</title>
  </head>
  <body>
    <h1>Help</h1>
    <p>
      Get help on the Ruby on Rails Tutorial at the
      <a href=”https://railstutorial.jp/help”>Rails Tutorial help       page</a>.
      To get help on this sample app, see the
      <a href=”https://railstutorial.jp/#ebook”>
      <em>Ruby on Rails Tutorial</em> book</a>.
    </p>
  </body>
</html>
app/views/static_pages/about.html.erbの内容
<!DOCTYPE html>
<html>
  <head>
    <title>About | Ruby on Rails Tutorial Sample App</title>
  </head>
  <body>
    <h1>About</h1>
    <p>
      <a href=”https://railstutorial.jp/”>Ruby on Rails Tutorial</a>
      is a <a href=”https://railstutorial.jp/#ebook”>book</a> and
      <a href=”https://railstutorial.jp/screencast”>screencast</a>
      to teach web development with
      <a href=”https://rubyonrails.org/”>Ruby on Rails</a>.
      This is the sample app for the tutorial.
    </p>
  </body>
</html>
本来のhtmlは上の例の様に<!DOCTYPE html>が入り<head>と<body>タグが入る。でテスト
$ rails test
前略
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips
これでエラーは出なくなった。 現在のtest/controllers/static_pages_controller_test.rbの内容は
require “test_helper”
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test “should get home” do
    get static_pages_home_url
    assert_response :success
    assert_select “title”, “Home | Ruby on Rails Tutorial Sample App”
  end

 

  test “should get help” do
    get static_pages_help_url
    assert_response :success
    assert_select “title”, “Help | Ruby on Rails Tutorial Sample App”
  end

  test “should get about” do
    get static_pages_about_url
    assert_response :success
    assert_select “title”, “About | Ruby on Rails Tutorial Sample App”
  end
end
ハイライトしている部分が同じような繰り返しになっているので、setupと言う特別なメソッドを使い改良
$ gedit test/controllers/static_pages_controller_test.rb
require “test_helper”
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  
def setup 
          ←ここから
    @base_title = “Ruby on Rails Tutorial Sample App”
  end
              ←ここまで追記
  test “should get home” do
   
get static_pages_home_url
    assert_response :success
   
assert_select “title”, “Home | #{@base_title}”  ←変更
  end
  test “should get help” do
    get static_pages_help_url
    assert_response :success
   
assert_select “title”, “Help | #{@base_title}”  ←変更
  end
  test “should get about” do
    get static_pages_about_url
   
assert_response :success
    assert_select “title”, “About | #{@base_title}”
  ←変更
  end
end
まだ重複しているが、完全に同じでは内が、Railsのprovideメソッドを使ってタイトルをページごとに変更し、なるべく同じようにします。
$ gedit app/views/static_pages/home.html.erb
<% provide(:title, “Home”) %>  ←追記
<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title> ←変更
  </head>
  <body>
    <h1>Sample App</h1>
    <p>
      This is the home page for the
      <a href=”https://railstutorial.jp/”>Ruby on Rails Tutorial</a>
      sample application.
    </p>
  </body>
</html>

テストする
$ rails test
前略
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips
エラーは出ていない。HelpページとAboutページも同様に変更します
$ gedit app/views/static_pages/help.html.erb
<% provide(:title, “Help”) %>   ←追記
<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>  ←変更
  </head>
  <body>
    <h1>Help</h1>
    <p>
      Get help on the Ruby on Rails Tutorial at the
      <a href=”https://railstutorial.jp/help”>Rails Tutorial help
      page</a>.
      To get help on this sample app, see the
      <a href=”https://railstutorial.jp/#ebook”>
      <em>Ruby on Rails Tutorial</em> book</a>.
    </p>
  </body>
</html>
$ gedit app/views/static_pages/about.html.erb
<% provide(:title, “About”) %>   ←追記
<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>  ←変更
  </head>
  <body>
    <h1>About</h1>
    <p>
      <a href=”https://railstutorial.jp/”>Ruby on Rails Tutorial</a>
      is a <a href=”https://railstutorial.jp/#ebook”>book</a> and
      <a href=”https://railstutorial.jp/screencast”>screencast</a>
      to teach web development with
      <a href=”https://rubyonrails.org/”>Ruby on Rails</a>.
      This is the sample app for the tutorial.
    </p>
  </body>
</html>
変更していたレイアウトファイルを次のコマンドでファイル名を元に戻す
$ mv layout_file app/views/layouts/application.html.erb
レイアウトファイルを変更する
$ gedit app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>  ←変更
    <meta name=”viewport” content=”width=device-width,initial-scale=1″>  ←変更
    <meta charset=”utf-8″>  ←変更
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag “application”, “data-turbo-track”: “reload” %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>
ここに出てきた、<%= yield %>、<%= csrf_meta_tags %>、<%= csp_meta_tag %>、<%= stylesheet_link_tag “application”, “data-turbo-track”: “reload” %> 等はチュートリアルを見て理解してください。
そしてテスト
$ rails test
前略
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips

localhost:3000にアクセスしたらhoeを表示する様にする
$ gedit config/routes.rb
Rails.application.routes.draw do
  root “static_pages#home”   ←追記
  get ‘static_pages/home’
  get ‘static_pages/help’
  get “static_pages/about”
  get “static_pages/contact”
  root “application#hello”   ←削除する
end
ブラウザでhttp://localhost:3000/にアクセスする
 
getに登録
$ git add -A
$ git commit -m “Latest”

minitest reportersを使うとテスト結果の出力を見やすくフォーマットしてくれます。そのため
$ gedit test/test_helper.rb
ENV[“RAILS_ENV”] ||= “test”
require_relative “../config/environment”
require “rails/test_help”
require “minitest/reporters”   ←追記
Minitest::Reporters.use!       ←追記

class ActiveSupport::TestCase
  # Run tests in parallel with specified workers
  parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here…
end
$ rails test
Running 5 tests in a single process (parallelization threshold is 50)
Started with run options –seed 58624

5/5: [===================================] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.27512s
5 tests, 9 assertions, 0 failures, 0 errors, 0 skips

チューとリルではGuardによるテストの自動化を行って降りますが、私は飛ばしました(設定が良くわからないので、後日勉強とします)

 

カテゴリー: Ruby on railsに挑戦(almalinux9) | コメントする

5:最初のテスト

rails generate controllerを実効した時点でテストが出来ている
$ ls test/controllers/
static_pages_controller_test.rb
見てみよう
$ cat test/controllers/static_pages_controller_test.rb
require “test_helper”

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
 test “should get home” do
  get static_pages_home_url
  assert_response :success
 end

 test “should get help” do
  get static_pages_help_url
  assert_response :success
 end
end
$
rails test
Running 2 tests in a single process (parallelization threshold is 50)
Run options: –seed 6539
# Running:
..
Finished in 0.506600s, 3.9479 runs/s, 3.9479 assertions/s.
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

db/test.sqlite3が出来ているので、Gitリポジトリに登録されると邪魔なのですが、.gitignoreに既にイグノアーされる記述が入っている
.gitignoreファイルの抜粋
# Ignore the default SQLite database.
/db/*.sqlite3
/db/*.sqlite3-*
テスト駆動開発のサイクルは「失敗するテストを最初に書く」「次にアプリケーションのコードを書いて成功させる(パスさせる)」「必要ならリファクタリングする」のように進みます。多くのテストツールでは、テストの失敗を red 、成功したときを green で表します。ここから、このサイクルを「 redgreen ・REFACTOR」と呼ぶこともあります。これに従って最初のサイクルを完了させましょう。まず失敗するテストを書いて red になるようにします。
$ gedit test/controllers/static_pages_controller_test.rb
require “test_helper”

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test “should get home” do
    get static_pages_home_url
    assert_response :success
end

  test “should get help” do
    get static_pages_help_url
    assert_response :success
  end

  test “should get about” do
    get static_pages_about_url
    assert_response :success
  end
end
$ rails test
前略
NameError: undefined local variable or method `static_pages_about_url’
中略
3 runs, 2 assertions, 0 failures, 1 errors, 0 skips
エラーを見るとstatic_pages_about_urlのURLが無いと言っているのでabout用のルーティングを追加する
$ gedit test/controllers/static_pages_controller_test.rb
Rails.application.routes.draw do
 get ‘static_pages/home’
 get ‘static_pages/help’
 get “static_pages/about”   ←これを追記
root “application#hello”
end
そしてテスト
$ rails test
前略
AbstractController::ActionNotFound: The action ‘about’ could not be found for StaticPagesController
中略
3 runs, 2 assertions, 0 failures, 1 errors, 0 skips
今度のエラーはaboutのコントローラーが無いと言っているので
$ gedit app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
  def home
  end

  def help
  end

  def about   ← aboutを追記
  end
end
そしてテスト
$ rails test
1) Error:
StaticPagesControllerTest#test_should_get_about:
ActionController::MissingExactTemplate: StaticPagesController#about is 3 runs, 2 assertions, 0 failures, 1 errors, 0 skips
今度はaboutのテンプレートが無いといっているので
$ gedit app/views/static_pages/about.html.erb
こんなファイルは無いので空白のページが表示されるので、作る
<h1>About<h1>
<p>
<a href=“https://railstutorial.jp/”>Ruby on Rails Tutorial</a>
 is a <a href=“https://railstutorial.jp/#ebook”>book</a> and

 <a href=“https://railstutorial.jp/screencast”>screencast</a>
 to teach web development with

 <a href=“https://rubyonrails.org/”>Ruby on Rails</a>.
 This is the sample app for the tutorial.
</p>
で、テスト
$ rails test
前略
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips
無事エラーがゼロになった。そしてブラウザにhttp://localhost:3000/static_pages/aboutと入力すると

と表示された。

カテゴリー: Ruby on railsに挑戦(almalinux9) | コメントする

4:ほぼ静的なページの作成

サンプルアプリケーションを生成する
$ cd ..
$ pwd
/Rails/environment
$ rails _7.0.6_ new sample_app –skip-bundle
create
    create README.md
    create Rakefile
    create .ruby-version
   後略
$ cd sample_app/
Gmfileの編集
$ gedit Gemfile
source “https://rubygems.org”
git_source(:github) { |repo| “https://github.com/#{repo}.git” }

gem “rails”, “7.0.6”
gem “sassc-rails”, “2.1.2”
gem “sprockets-rails”, “3.4.2”
gem “importmap-rails”, “1.1.0”
gem “turbo-rails”, “1.1.1”
gem “stimulus-rails”, “1.0.4”
gem “jbuilder”, “2.11.5”
gem “puma”, “5.6.4”
gem “bootsnap”, “1.12.0”, require: false

group :development, :test do
gem “sqlite3”, “1.4.2”
gem “debug”, “1.5.0”, platforms: %i[ mri mingw x64_mingw ]
end

group :development do
gem “web-console”, “4.2.0”
end

group :test do
gem “capybara”, “3.37.1”
gem “selenium-webdriver”, “4.2.0”
gem “webdrivers”, “5.0.0”
gem “rails-controller-testing”, “1.0.5”
gem “minitest”, “5.15.0”
gem “minitest-reporters”, “1.5.0”
gem “guard”, “2.18.0”
gem “guard-minitest”, “2.4.6”
end

group :production do
gem “pg”, “1.3.5”
end
gemをインストール
$ bundle _2.3.14_ config set –local without ‘production’
$ bundle _2.3.14_ install
Fetching gem metadata from https://rubygems.org/………..
Resolving dependencies…….
Using rake 13.0.6
Using concurrent-ruby 1.2.2
後略

gitにコミット
$ git init
Reinitialized existing Git repository in /Rails/environment/sample_app/.git/
$ git add -A
$ git commit -m “Initialize repository”
[main (root-commit) 70d02f5] Initialize repository
70 files changed, 1235 insertions(+)
create mode 100644 .gitattributes
create mode 100644 .gitignore
create mode 100644 .ruby-version
create mode 100644 Gemfile
後略
README.md
を書き換えてみる
$ gedit README.md
# Ruby on Rails チュートリアルのサンプルアプリケーション

これは、次の教材で作られたサンプルアプリケーションです。
[*Ruby on Rails チュートリアル*](https://railstutorial.jp/)
(第7版)
[Michael Hartl](https://www.michaelhartl.com/) 著

ライセンス
後略
この変更をコミットする
$ git commit -am “Improve the README”
[main 7cba1a8] Improve the README
1 file changed, 37 insertions(+), 13 deletions(-)
helloアクションをApplicationコントローラーに追加する
$ gedit app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def hello
render html: “hello, world!”
end
end
ルーティングを設定する
$ gedit config/routes.rb
Rails.application.routes.draw do
  root “application#hello”
end
そしてコミット
$ git commit -am “Add hello”
[main b394c69] Add hello
2 files changed, 4 insertions(+), 4 deletions(-)
バンドルをロック
$ bundle _2.3.14_ lock –add-platform x86_64-linux
Writing lockfile to /Rails/environment/sample_app/Gemfile.lock
ブランチを作成
$ git switch -c static-pages
Switched to a new branch ‘static-pages’
StaticPagesコントローラを生成する
$ rails generate controller StaticPages home help
  create app/controllers/static_pages_controller.rb
  route get ‘static_pages/home’
    get ‘static_pages/help’
  invoke erb
後略
これでapp/controllers/static_pages_controller.rbにhomeとhelpが追加される

gitにコミット
$ git add -A
$ git commit -m “Add a Static Pages controller”
[static-pages 3020c96] Add a Static Pages controller
6 files changed, 28 insertions(+)
create mode 100644 app/controllers/static_pages_controller.rb
create mode 100644 app/helpers/static_pages_helper.rb
後略
そしてapp/controllers/static_pages_controller.rbを見てみると
class StaticPagesController < ApplicationController
 def home
 end

 def help
 end
end
とhomeとhelpのアクション(ブランクだが)が追加されている
ルートファイルにhomeとhelpの定義が追加されている。見てみよう
$ cat config/routes.rb
Rails.application.routes.draw do
 get ‘static_pages/home’
 get ‘static_pages/help’
 root “application#hello”
end
別ターミナルでserverが立ち上げっているのを確認後、http://localhost:3000/static_pages/homeにアクセスすると

このページはコントローラーのhomeによって呼び出されたapp/views/static_pages/home.html.erbの内容が表示されている
同様にhelpも同じ感じで表示される筈だ
HomeページのHTMLを修正する
$ gedit app/views/static_pages/home.html.erb
<h1>Sample App</h1>
<p>
  This is the home page for the
  <a href=”https://railstutorial.jp/”>Ruby on Rails Tutorial</a>
  sample application.
</p>
そしてブラウザからhttp://localhost:3000/static_pages/homeにアクセスすると

同様に
$ gedit app/views/static_pages/help.html.erb
<h1>Help</h1>
<p>
    Get help on the Ruby on Rails Tutorial at the
    <a href=”https://railstutorial.jp/help”>Rails Tutorial Help page</a>.
    To get help on this sample app, see the
   <a href=”https://railstutorial.jp/#ebook”><em>Ruby on Rails Tutorial</em>
    book</a>.
</p>
そしてブラウザから

カテゴリー: Ruby on railsに挑戦(almalinux9) | コメントする