LoginSignup
1
5

More than 3 years have passed since last update.

Rails 6で認証認可入り掲示板APIを構築する #3 RSpec, FactoryBot導入しpostモデルを作る

Last updated at Posted at 2020-09-07

Rails 6で認証認可入り掲示板APIを構築する #2 gitとrubocop導入

RSpec, FactoryBotのインストール

前回の続きから。
テストに使うRSpecとFactoryBotを入れます。

Gemfile
 group :development, :test do
+  gem "rspec-rails"
+  gem "factory_bot_rails"
 end
$ bundle

インストールできたので初期化をします。

$ rails g rspec:install
...
Running via Spring preloader in process 6770
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb

今後modelやcontrollerを生成した時に、一緒に自動生成されるRSpecの制御をします。
最低限のテストに収めるためmodelとrequestのみでいこうと思うので、それ以外を使わないよう設定します。

config/application.rb
  class Application < Rails::Application
...

+   config.generators do |g|
+     g.test_framework :rspec, 
+       view_specs: false, 
+       helper_specs: false, 
+       controller_specs: false, 
+       routing_specs: false
+   end
  end
...

ついでにFactoryBotをRSpecの中でクラスを書かなくてもメソッドが使える設定をします。

spec/rails_helper.rb
 RSpec.configure do |config|
+  config.include FactoryBot::Syntax::Methods
...

参考:RailsアプリへのRspecとFactory_botの導入手順

ここまでいったらrubocop動かしてエラー潰し、エラーがゼロになったらgit commitしておきましょう。
なおrubocop -aの-aは自動修正可能なものを自動修正するコマンドなので、1回目大量のエラーが出て場合、もう1回動かすと自動修正後で数が一気に減るはずです。

postモデルの生成

前準備が非常に長かったですが、これでようやく準備が整ったのでmodelを作っていきます。

$ rails g model Post subject:string body:text

こちらのコマンドを実行するとmodel, migration, spec, factory_botの4ファイルが
生成されます。

$ rails db:migrate

もし実行時に以下エラーが出たら、postgresが止まっているので起動します

rails aborted!
PG::ConnectionBad: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql
...

$ sudo service postgresql95 start

pryを入れる

rails consoleコマンドを実行時、標準のirbよりもpryの方ができることが増えます。

Gemfile
group :development, :test do
+   gem "pry-rails"
+   gem "pry-byebug"
...
end
$ bundle

rails consoleでpostの保存ができるか試す

controllerまで実装して動作確認だと手間がかかるので、rails consoleでmodelがDBに保存・読み込みができるか試します。

$ rails c
...
[1] pry(main)> Post.create!(subject: "hoge", body: "fuga")
[2] pry(main)> posts = Post.all
  Post Load (0.6ms)  SELECT "posts".* FROM "posts"
=> [#<Post:0x0000000006e89850
  id: 1,
  subject: "hoge",
  body: "fuga",
  created_at: Sat, 05 Sep 2020 13:50:01 UTC +00:00,
  updated_at: Sat, 05 Sep 2020 13:50:01 UTC +00:00>]

[1]でpostを1件保存し、[2]で全件取得しました。
どうやら正常にcreate, readができていそうですね。

続き

Rails 6で認証認可入り掲示板APIを構築する #4 postのバリデーション、テスト実装

連載目次へ

1
5
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
1
5