Reflection to Tealeaf Course3 Week3
In week 2, Tealeaf talked about how to test controller, and this week, I got a more comprehensive test consideration for controller and user interaction.
###For Controller Test
- Everytime add a function feature, also need to add a test for it.
- Everytime find a bug, also add a test for it.
###DRY
RSpec also offer two ways to DRY code.
- Macro
1 | $ mkdir spec/support |
And we can move repeatedly code into here, for example, we usually need to set a login user:
1 | def set_current_user(user = nil) |
and find user
1 | def current_user |
- Shared Examples
1 | $ touch spec/support/share_examples.rb |
A test method may be called through different controllers:
1 | shared_examples 'requre_sign_in' do |
Be careful: action
is a variable, then when using it:
1 | it_behaves_like 'require_sign_in' do |
###Feature Specs
There are two methods to test user interactions, one is request spec
and this is deprecated by Capybara. The other one is feature specs
, recommended by Capybara.
Capybara offer functions that we can click link/button, fill text field…etc, to interactive with UI.
- Install Capybara gem
1 | group :test |
Also add this line to test helper file
1 | requrire 'capybara/rails' |
And
1 | $mkdir spec/features |
- A sample for user operation:
1 | feature 'user interacts with the queue' do |
here I choose to use :xpath
.
- One level for scenario
In above sample, I extract methods add_video_to_queue
, set_video_order
, and expect_video_order
. This is we want to keep a principle Abstract one level for scenario
. Encapsulating logic code and keep main code readable on the same abstract level can help reader to review.
###Rails Conventions
- Merge Params
1 | = form_tag update_queue_path do |
Then we will get a hash value params[queue_items] = {position: xxx, id: xxx}
- select_tag
1 | %td= select_tag 'queue_items[][rating]', options_for_video_reviews(queue_item.rating), include_blank: true |
And options_for_video_reviews
:
1 | def options_for_video_reviews(selected = nil) |
Be careful that [pluralize(num, 'Star'), num]
is a pair value.
- ActiveRecord Transactions
A sample from Rails Tutorial
1 | ActiveRecord::Base.transaction do |
If any one of david.withdrawl
or mary.deposit
raise an exception(Be careful: there must be a raising error to trigger transaction), all database record in this action will be rollback. It deal with batch action with database. So I have to care about what functions will raise an exception when fail. Ex. update
return a fail, and update!
raise an exception.