From the continuation of the last time. Put in the RSpec and FactoryBot to use for testing.
Gemfile
group :development, :test do
+ gem "rspec-rails"
+ gem "factory_bot_rails"
end
$ bundle
Now that it has been installed, initialize it.
$ 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
When you generate a model or controller in the future, it will control the RSpec that is automatically generated together. I'm going to use only model and request to keep the test to a minimum, so set not to use anything else.
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
...
Next, set FactoryBot so that the method can be used without writing a class in RSpec.
spec/rails_helper.rb
RSpec.configure do |config|
+ config.include FactoryBot::Syntax::Methods
...
Reference: Procedure for installing Rspec and Factory_bot in Rails app
At this point, run rubocop to eliminate the error, and when the error becomes zero, git commit.
Note that -a in rubocop -a
is a command that automatically corrects what can be automatically corrected, so if you get a large number of errors the first time, if you move it again, the number should decrease at once after the automatic correction.
The preparation was very long, but now that we are ready, we will make a model.
$ rails g model Post subject:string body:text
When you execute this command, 4 files of model, migration, spec and factory_bot will be displayed. Will be generated.
$ rails db:migrate
If you get the following error at runtime, postgres is stopped and will start
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
When running the rails console command, pry can do more than standard irb.
Gemfile
group :development, :test do
+ gem "pry-rails"
+ gem "pry-byebug"
...
end
$ bundle
It takes time to implement up to the controller and check the operation, so try to see if the model can be saved and loaded in the DB with the rails console.
$ 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>]
I saved one post in [1] and got all in [2]. Apparently you can create and read normally.