
© 2019 Martin J.
Dürst 青山学院大学
ミニテスト
- デスクトップPC (強く推薦) 又はノートPCで https://moo.sw.it.aoyama.ac.jp/
にログイン済み
- ナビゲーションは左に畳み、ブラウザは全画面に拡大
- もう片方のマシーンで電源を切る
(ノートPCの場合、鞄に)
- 授業開始まで教科書、資料、筆箱、財布などを鞄に入れ、鞄は床に
- テスト終了後はマウス・キーボードに一切触らないこと
Today's Schedule
- Minitest
- Last week's exercises and homework
- Model generation
- Validation
- Testing
- Today's exercises
Last Lecture's Exercises
Ideal split between controller and view:
- Controller creates/calculates/prepares data (
@time or
@count)
- View takes care of display (repetitions, formatting)
Model Generation
- Last week, we generated a controller (
SayController in
app/controllers/say_controller.rb) with
rails generate controller Say hello
(rails generate controller Controller
action)
- Today, we will generate a model with e.g.
rails generate model Wrestler name:string height:decimal
...
(rails generate model Model
field1:type1 field2:type2
...)
- The types are generic types that work for ActiveRecord, Ruby, and various
databases
Rails Datatypes
The main datatypes that can be used for model generation are as follows:
| Label |
Usage/Meaning |
| :string |
(relatively short) character string |
| :text |
(long) character string |
| :binary |
(long) binary string |
| :date |
date (year/month/day) |
| :datetime |
date and time |
| :time |
time (of day) only |
| :timestamp |
date and time, for administrative purposes |
| :decimal |
decimal (with a fixed number of decimals before and after the decimal
point) |
| :integer |
integer |
| :float |
float/double |
| :boolean |
boolean (single bit) |
Validation
Example Validations
(more at https://guides.rubyonrails.org/active_record_validations.html)
- Make sure the data is present:
presence: true
- Make sure the data is numeric:
numericality: true
- Make sure a number is integral:
numericality: { only_integer: true
}
- Allow absent (nil) data for numbers:
numericality: { allow_nil:
true }
- Check for value range:
numericality: { greater_than: 50
}
- Check for a fixed set of values:
inclusion: { in: ['序の口',
'序二段', ...] }
Testing
- Testing programs is very important, for the following reasons:
- Makes expectations clear
- Helps catch misunderstandings
- Helps catch future incompatible changes
- Many software companies employ more testers than programmers
- Writing tests while writing programs is very efficient
Testing in Rails
- Rails comes with a setup (environment) for testing
- Generators (rails generate ...) automatically create the necessary test
files
- The actual tests have to be written by hand (because there is not enough
domain knowledge)
- We will write tests for a model today
Rails Model Tests
(more at https://guides.rubyonrails.org/testing.html#model-testing
and other parts of that Web page; see also documentation for Minitest)
- Model tests go into the file
test/models/model_test.rb, e.g.
test/models/wrestler_test.rb
- Tests are run with
rails test; it is possible to run only
model tests with rails test:models
- All tests are created by calling the method
test in a class
ModelTest (e.g. WrestlerTest), which is a
subclass of ActiveSupport::TestCase
- The method
test takes a description string and a block
(do...end)
- The block contains one or more assertions
- Assertions can be
assert, assert_equal, and
many more
- The
setup method can be used to create some data that can be
reused in some or all of the tests (use instance variables to access the
data in test methods)
- After checking for validity (
assert
hoge.(in)valid?), error details
can be checked with
assert hoge.errors[:real_name].any?
or
assert_equal ["must be greater than 50"],
hoge.errors[:height]
Exercise 8a: Setting up the Actor Model
- Create a rails application named
acting.
- Create a model named
Actor with the following fields (in
this order!):
name, real_name (本名),
birth_date, origin, height,
weight, gender (male or
female), blood_type
(A/B/O/AB)
- The fields should have the following types:
- name, real_name, origin, gender, and blood_type should be strings
- height should be an integer
- weight should be a decimal
- birth_date should be a date
- Hint: There may be an error message regarding
Clusivity. You
can ignore it.
- Use
rails db:migrate to generate the database
- Using your editor and SQLiteStudio, have a look at the following:
db/schema.rb
db/migrate/20190603HHMMSS_create_actors.rb
db/development.sqlite3 (in particular the Structure
tab)
- Check that the order and type of the fields is correct
(there will be three additional fields, id,
created_at, and updated_at, which are generated
and used automatically by Rails)
- If the order and types are not correct, delete the application and start
again
- Submit the file
schema.rb Moodle (deadline: 17:00).
Exercise 8b: Adding Validations
- Download the files
actors_controller.rb,
new.html.erb, and show.html.erb (you have to
create a directory actors in app/view)
- Add the following line to config/routes.rb:
resources :actors
- Start the server and direct a browser at
http://localhost:3000/actors/new
- Add some data, including data that doesn't make sense (e.g. non-existent
genders or blood types, out-of-range height, weight, or birth dates,...) or
data where some fields are just missing.
- Check the data with SQLiteStudio (Data tab, Grid view, use the blue
button in the upper left corner for updates)
- One-by-one, add the following validations to your model. For each
validation, check that you get an appropriate error message. Also, check
that the error message goes away when you fix the error.
- Check presence for all fields except weight (some actors and
actresses don't want to make their weight public)
- Check for sensible lower and upper bounds for birth_date, height, and
weight (if present)
- Check for allowed values for gender and blood_type
- Submit the file
app/models/actor.rb to Moodle (deadline:
18:00)
- Submit your model file before the deadline, with as many validations as
possible
Exercise 8c: Adding Tests
- Run
rails db:migrate RAILS_ENV=test to set up the test
database
- Run
rails test. You should get 0 runs, 0 asssertions,
0 failures, 0 errors, 0 skips.
- If there is a long error message relating to chromedriver-helper, do the
following:
- Remove the file
Gemfile.lock
- In
Gemfile, comment out the lines relating to
capybara, selenium-webdriver, and
chromedriver-helper
- Run
bundle install
- One-by-one, in the file
test/models/actor_test.rb, add tests
for the following. Make sure that for each test, you check that it fails
(when the corresponding validation is commented out) and that it succeeds
(when the corresponding validation is not commented out). Try to use many
calls to test, with only very few assertions per call.
- Actor fields must not be empty (except weight; make sure you have a
test for each field)
- birth_date, height, and weight have to be inside the bounds defined
in the validation
- Error messages are equal to the messages that Rails actually
sends
- Submit the file
test/models/actor_test.rb to Moodle
(deadline: 19:00)
- Submit your test file before the deadline, with as many tests/assertions
as possible
Exercise 8d: Add Data to Database
- Make sure all the valitations are activated, and your tests work
- Using SQLiteStudio, delete all the data from the database (most of it is
bogus, anyway)
- Using your application, add 5 real actors/actresses with correct data to
the database
- You can get real data from Wikipedia or IMDB,...
- There will be a deduction if two or more students provide data for the
same actor/actress
- Submit the database file (
db/development.sqlite3) to Moodle
(deadline Wednesday, 19:00)
Homework
- Study the files that were generated with
rails generate model
.... Try to get an idea about what each line in each file
means. (you do not have to read documentation for this homework, but you
may occasionally have to consult a dictionary)
- Think about Web applications that you might want to create (using Rails
or any other technology). Write down your ideas.