Slide 1

Slide 1 text

RSPEC FOR THE PRACTICAL RUBYIST EXPLAINING SIMPLY AND QUICKLY ALL THE ELEMENTS OF CONTROLLER, MODEL, VIEW, HELPER, INTEGRATION, FEATURE WITHout ANSWERS TO PROBLEMS

Slide 2

Slide 2 text

2015!!! RubyConFTW

Slide 3

Slide 3 text

rubytaiwan/taipei Things to know about Taipei put together by Ruby Taiwan Community Inspired from RubySG/Singapore

Slide 4

Slide 4 text

Juanito Fatas !

Slide 5

Slide 5 text

juanitofatas/fast-ruby Collection of Idioms, Benchmarks, etc. for Faster Ruby Code Inspired by @sferik and Ruby Community

Slide 6

Slide 6 text

Employee #1

Slide 7

Slide 7 text

The Birth of deppbot

Slide 8

Slide 8 text

JuanitoFatas/rubygems.org/pull/1

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

JOIN OPEN SOURCE

Slide 13

Slide 13 text

Tweet at Me @juanitofatas " #rubyconFTW #rubyconFTW2015

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

Introducing 4K Live Photos iPhone 6S Plus

Slide 16

Slide 16 text

muan/mojibar

Slide 17

Slide 17 text

Emoji is Awesome!

Slide 18

Slide 18 text

95% of time preparations of this talk

Slide 19

Slide 19 text

Tweak fonts and think about emojis

Slide 20

Slide 20 text

First of all

Slide 21

Slide 21 text

It’s been a tough day

Slide 22

Slide 22 text

%

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

Some mathematics

Slide 25

Slide 25 text

My first talk ever, 5-minute long ⏳

Slide 26

Slide 26 text

My second talk, 50-minute long

Slide 27

Slide 27 text

Let ψ = 5

Slide 28

Slide 28 text

Let ω = 50

Slide 29

Slide 29 text

ω — ψ =

Slide 30

Slide 30 text

50 — ψ =

Slide 31

Slide 31 text

50 — 5 =

Slide 32

Slide 32 text

50 — 5 =10

Slide 33

Slide 33 text

Slide 34

Slide 34 text

I am a 10x Speaker

Slide 35

Slide 35 text

Q.E.D.

Slide 36

Slide 36 text

Matz is Great! ,,,,,,

Slide 37

Slide 37 text

Talk Title Origin

Slide 38

Slide 38 text

Richard Feynman

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

RSPEC FOR THE PRACTICAL RUBYIST EXPLAINING SIMPLY AND QUICKLY ALL THE ELEMENTS OF CONTROLLER, MODEL, VIEW, HELPER, INTEGRATION, FEATURE WITHout ANSWERS TO PROBLEMS

Slide 41

Slide 41 text

Why This Talk

Slide 42

Slide 42 text

Rubyists in Taiwan are courageous.

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

Raise the awareness of Testing in Thiland

Slide 45

Slide 45 text

Journey into Rails Testing ⛵0

Slide 46

Slide 46 text

Introductory Talk No theory, and TDD because How-to, but not what & why Tutorial type

Slide 47

Slide 47 text

Just Enough Background

Slide 48

Slide 48 text

correctness quality buying time for the future finding regressions save repeated labor gives you confidence easy refactoring perfect bug report live documentation drive your implementation automation is win ✨

Slide 49

Slide 49 text

The Rabbit Hole

Slide 50

Slide 50 text

What is RSpec "

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

https://relishapp.com/rspec RSpec Core | RSpec Expectations | RSpec Mocks | RSpec Rails

Slide 53

Slide 53 text

RSpec Minitest vs

Slide 54

Slide 54 text

A professional developer should be able to work in either one of these because they essentially do the same thing: test your code. — Dr.Tenderlove “ http://tenderlovemaking.com/2015/01/23/my-experience-with-minitest-and-rspec.html

Slide 55

Slide 55 text

class Something < Minitest::Test def test_works assert_equal 11, 10 end def test_really_works assert_equal 11, 11 end end (Unit)Test

Slide 56

Slide 56 text

Test cases are Class Minitest::Test Tests are methods inside test case

Slide 57

Slide 57 text

describe "something" do it "works" do expect(11).to equal(10) end it "really works" do expect(11).to equal(11) end end Spec(ification)

Slide 58

Slide 58 text

Test cases are describe with description string / actual object and a block of tests Tests are it with description string and the body of test (block)

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

RSpec RAILS

Slide 61

Slide 61 text

A Gentle Introduction to RSpec

Slide 62

Slide 62 text

rspec rspec-core rspec-expectations rspec-mocks MetaRubyGem

Slide 63

Slide 63 text

How to run

Slide 64

Slide 64 text

. means Passed F means Failure E means Error * means Pending S means Skip

Slide 65

Slide 65 text

Sample Output

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

$ rspec --init

Slide 68

Slide 68 text

.rspec --color --require spec_helper https://relishapp.com/rspec/rspec-core/v/3-3/docs/command-line/

Slide 69

Slide 69 text

spec/ spec_helper.rb

Slide 70

Slide 70 text

Magic Spells

Slide 71

Slide 71 text

Computer science is a terrible name for this business. First of all, it's not a science. It might be engineering or it might be art, but we'll actually see that computer so-called science actually has a lot in common with magic.— Hal Abelson “ https://youtu.be/2Op3QLzMgSY?t=27s

Slide 72

Slide 72 text

describe it expect to

Slide 73

Slide 73 text

describe it expect to a series of tests

Slide 74

Slide 74 text

describe it expect to a series of tests is a test

Slide 75

Slide 75 text

describe it expect to a series of tests is a test an actual object

Slide 76

Slide 76 text

describe it expect to a series of tests is a test an actual object match something

Slide 77

Slide 77 text

describe how methods works, group of test examples, series of behaviour

Slide 78

Slide 78 text

describe User do ... end

Slide 79

Slide 79 text

RSpec.describe describe config.disable_monkey_patching! in spec_helper.rb 34QFD

Slide 80

Slide 80 text

RSpec.describe User do describe ".authenticate" do ... end describe "#name" do ... end end describe can be nested

Slide 81

Slide 81 text

RSpec.describe User do describe ".authenticate" do ... end describe "#name" do ... end end

Slide 82

Slide 82 text

RSpec.describe User do describe ".authenticate" do ... end describe "#name" do ... end end

Slide 83

Slide 83 text

RSpec.describe User do describe ".authenticate" do ... end describe "#name" do ... end end

Slide 84

Slide 84 text

RSpec.describe User do describe ".authenticate" do ... end describe "#name" do ... end end

Slide 85

Slide 85 text

RSpec.describe User do describe ".authenticate" do ... end describe "#name" do ... end end

Slide 86

Slide 86 text

context scenarios in your implementation same as describe

Slide 87

Slide 87 text

context "when…" do ... end context "with…" do end

Slide 88

Slide 88 text

it a single test example inside of describe / context block

Slide 89

Slide 89 text

it "eats something" do ... end

Slide 90

Slide 90 text

describe SteveJobs do context "with stylus" do it "yucks" do end end end

Slide 91

Slide 91 text

$ bin/rspec spec/models/steve_jobs_spec.rb --format doc SteveJobs with stylus yucks

Slide 92

Slide 92 text

it "hello" do … end 4JOHMF-JOF .VMUJ-JOF it { … }

Slide 93

Slide 93 text

example "" do ... end "WPJE specify "" do ... end

Slide 94

Slide 94 text

before things to do before test run

Slide 95

Slide 95 text

before { ... } it "" do ... end

Slide 96

Slide 96 text

before do ... end it "" do ... end

Slide 97

Slide 97 text

after things to do after test run

Slide 98

Slide 98 text

it "" do ... end after { ... }

Slide 99

Slide 99 text

it "" do ... end after do … end

Slide 100

Slide 100 text

inside of it

Slide 101

Slide 101 text

Expectations & matchers come in

Slide 102

Slide 102 text

expect(actual) expect something

Slide 103

Slide 103 text

to eq(expected) to equal what we expected

Slide 104

Slide 104 text

it "…" do expect(1+1).to eq(2) end from rspec-expectations

Slide 105

Slide 105 text

it "…" do expect(1+1).to eq(2) end matcher

Slide 106

Slide 106 text

expect(1+1).to eq(2)

Slide 107

Slide 107 text

1+1 is 2? Let’s prove

Slide 108

Slide 108 text

162 pages to prove 1+1=2

Slide 109

Slide 109 text

it "…" do expect(1+1).to eq(2) end Example instance http://git.io/vZfvX

Slide 110

Slide 110 text

it "…" do self.expect(1+1).to self.eq(2) end Example Example

Slide 111

Slide 111 text

it "…" do self.expect(1+1).to self.eq(2) end instance of ExpectationTarget http://git.io/vZffB

Slide 112

Slide 112 text

ET = ExpectationTarget class Example def self.expect(actual) ET.new(actual) end end

Slide 113

Slide 113 text

ET = ExpectationTarget class Example def self.expect(actual) ET.new(actual) end end

Slide 114

Slide 114 text

ET = ExpectationTarget class Example def self.expect(actual) ET.new(actual) end end

Slide 115

Slide 115 text

class ET attr_reader :actual def initialize(actual) @actual = actual end end

Slide 116

Slide 116 text

it "…" do self.expect(1+1).to self.eq(2) end Example

Slide 117

Slide 117 text

it "…" do self.expect(1+1).to self.eq(2) end Matcher

Slide 118

Slide 118 text

class Example def self.eq(expected) EqMatcher.new(expected) end end EqMatcher is actually BuiltIn::Eq http://git.io/vZffi

Slide 119

Slide 119 text

class EqMatcher def initialize(expected) @expected = expected end def matches ... end end

Slide 120

Slide 120 text

it "…" do self.expect(1+1).to self.eq(2) end instance of ExpectationTarget

Slide 121

Slide 121 text

it "…" do self.expect(1+1).to self.eq(2) end ExpectationTarget#to

Slide 122

Slide 122 text

class ExpectationTarget def to(matcher) Postive.handle_matcher(actual, matcher) end end

Slide 123

Slide 123 text

class ExpectationTarget def to(matcher) Postive.handle_matcher(actual, matcher) end end Postive is actually PositiveExpectationHandler http://git.io/vZfJK

Slide 124

Slide 124 text

class Positive def self.handle_matcher(actual, matcher) matcher.matches(actual) end end http://git.io/vZqoX

Slide 125

Slide 125 text

class Positive def self.handle_matcher(actual, matcher) matcher.matches(actual) end end

Slide 126

Slide 126 text

class EqMatcher def matches(actual) match(expected, actual) end private def match(expected, actual) actual == expected end end

Slide 127

Slide 127 text

class EqMatcher def matches(actual) match(expected, actual) end private def match(expected, actual) actual == expected end end

Slide 128

Slide 128 text

class EqMatcher def matches(actual) match(expected, actual) end private def match(expected, actual) actual == expected end end http://git.io/vZfUp

Slide 129

Slide 129 text

voilà, old sport!

Slide 130

Slide 130 text

it "…" do expect(user.admin?).to be_true end `be` matcher be_true be_false be_truthy be_falsy be_nil be

Slide 131

Slide 131 text

eq eql equal be be_* match be_within start_with end_with be_instance_of be_kind_of respond_to raise_error throw_symbol include match_array contain_exactly cover change satisfy output yield_* https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers "1*

Slide 132

Slide 132 text

expect { code }.to raise_error(error, message) expect { post :create } .to raise_error( ActiveRecord::RecordInvalid, "Validation failed: name can't be blank" ) raise_error matcher

Slide 133

Slide 133 text

expect { code }.to change { something }.by(value) def do_request post :create, user: params end expect { do_request }.to change { User.count }.by(1) change matcher

Slide 134

Slide 134 text

RSpec predicate expect(user.admin?).to be_true expect(user).to be_admin

Slide 135

Slide 135 text

Read in English Most of the time There is a matcher for it ( VJEF

Slide 136

Slide 136 text

Stick with eq as a Starting Point ( VJEF KISS

Slide 137

Slide 137 text

expect(user.admin?).to be_true expect(user.admin?).to eq true

Slide 138

Slide 138 text

RSpec built-in matchers have better error messages ( VJEF

Slide 139

Slide 139 text

let lazily-evaluated block to shared object between tests

Slide 140

Slide 140 text

describe Baz let(:foo) { "bar" } it "…" do ... end end foo will be available in it blocks under the same scope!

Slide 141

Slide 141 text

let(:foo) { sleep 42 } it "…" do ... end Finished in 0.04424 seconds it "…" do ... end

Slide 142

Slide 142 text

let(:foo) { sleep 42 } it "…" do foo end Finished in 42.03924 seconds it "…" do ... end

Slide 143

Slide 143 text

let!(:foo) { sleep 42 } it "…" do ... end Finished in 42.03924 seconds it "…" do ... end

Slide 144

Slide 144 text

Prefer let over @instance_var ( VJEF

Slide 145

Slide 145 text

RSpec Mocks

Slide 146

Slide 146 text

RSpec Mocks To mock a mocking bird

Slide 147

Slide 147 text

We are dealing with objects and objects

Slide 148

Slide 148 text

collaborators of each other

Slide 149

Slide 149 text

Sometimes it costs a lot to setup collaborators

Slide 150

Slide 150 text

TDD Tired-Driven Development

Slide 151

Slide 151 text

Move Fast and Break Things drive slow but stay safe

Slide 152

Slide 152 text

Double

Slide 153

Slide 153 text

No content

Slide 154

Slide 154 text

A fake object for real object

Slide 155

Slide 155 text

RSpec::Mocks:: ExampleMethods #double http://git.io/vZq6F "1*

Slide 156

Slide 156 text

user = double("User")

Slide 157

Slide 157 text

Faking message and its return value

Slide 158

Slide 158 text

RSpec::Mocks:: ExampleMethods #allow http://git.io/vZq6F "1*

Slide 159

Slide 159 text

allow(obj).to receive(:msg).and_return(value)

Slide 160

Slide 160 text

user = double("User") allow(user).to receive(:admin?). and_return(true) allow(user).to receive(:admin?) { true }

Slide 161

Slide 161 text

user = double("User") allow(user).to receive(:admin?). and_return(true) allow(user).to receive(:admin?) { true }

Slide 162

Slide 162 text

user = double("User") allow(user).to receive(:admin?). and_return(true) allow(user).to receive(:admin?) { true }

Slide 163

Slide 163 text

user.admin? => true

Slide 164

Slide 164 text

user = double("User", admin?: true)

Slide 165

Slide 165 text

Stub & Mock

Slide 166

Slide 166 text

context "stub and mock" do describe "stub" do it "won't verify" do allow(User).to receive(:new) # User.new end end describe "mock" do it "will verify" do expect(User).to receive(:new) # User.new end end end

Slide 167

Slide 167 text

context "stub and mock" do describe "stub" do it "won't verify" do allow(User).to receive(:new) # User.new end end describe "mock" do it "will verify" do expect(User).to receive(:new) # User.new end end end Stub

Slide 168

Slide 168 text

context "stub and mock" do describe "stub" do it "won't verify" do allow(User).to receive(:new) # User.new end end describe "mock" do it "will verify" do expect(User).to receive(:new) # User.new end end end Mock

Slide 169

Slide 169 text

context "stub and mock" do describe "stub" do it "won't verify" do allow(User).to receive(:new) # User.new end end describe "mock" do it "will verify" do expect(User).to receive(:new) # User.new end end end Failure/Error: expect(User).to receive(:new) Mock

Slide 170

Slide 170 text

Mock will verify While Stub not

Slide 171

Slide 171 text

context "stub and mock" do describe "stub" do it "stub and verify" do allow(User).to receive(:new) User.new expect(User).to have_received(:new) end end end

Slide 172

Slide 172 text

context "stub and mock" do describe "stub" do it "won't verify" do allow(User).to receive(:new) User.new expect(User).to have_received(:new) end end end Strategy Spaces

Slide 173

Slide 173 text

Phases of Testing

Slide 174

Slide 174 text

setup exercise verify teardown everything we need the real work our expectations back to original state

Slide 175

Slide 175 text

Encrypt user password in database &YBN QMF

Slide 176

Slide 176 text

setup user = User.new(password: "passw0rd")

Slide 177

Slide 177 text

user.save exercise

Slide 178

Slide 178 text

expect(user.encrypted_password).to be_present verify

Slide 179

Slide 179 text

RSpec’ve got us covered teardown

Slide 180

Slide 180 text

before { user = User.new(password: "passw0rd") } it "should encrypt password" do user.save expect(user.encrypted_password).not_to eq nil end Put together

Slide 181

Slide 181 text

it "should encrypt password" do user = User.new(password: "passw0rd") user.save expect(user.encrypted_password).not_to eq nil end Strategy Spaces

Slide 182

Slide 182 text

Spy

Slide 183

Slide 183 text

Like 007, can do anything

Slide 184

Slide 184 text

Can respond to any messages

Slide 185

Slide 185 text

oo7 = spy oo7.can_jump? oo7.can_drive_car? oo7.can_play_poker? oo7.can_write_ruby?

Slide 186

Slide 186 text

spy is the Null Object of double spy = double.as_null_object

Slide 187

Slide 187 text

oo7 = spy oo7.hungry? expect(oo7).to have_received(:hungry?)

Slide 188

Slide 188 text

oo7 = spy oo7.tired? expect(oo7).to have_received(:tired?) Just like Stub!

Slide 189

Slide 189 text

RSpec 2 v.s RSpec 3 make stub and mock is confusing

Slide 190

Slide 190 text

But you can just try and explore their difference

Slide 191

Slide 191 text

That’s enough to write many tests!

Slide 192

Slide 192 text

RSpec & Rails

Slide 193

Slide 193 text

gem "rspec-rails" bundle rails generate rspec:install *OTUBMM in development and test group

Slide 194

Slide 194 text

spec/ rails_helper.rb Only when you need Rails

Slide 195

Slide 195 text

Try not to load rails_helper whenever possible 5JQ

Slide 196

Slide 196 text

config.infer_spec_type_from_file_location! # spec/models/user_spec.rb RSpec.describe User, type: :model do # automatically mixin functionalities end Infer type of test automatically

Slide 197

Slide 197 text

Metadata

Slide 198

Slide 198 text

RSpec.describe User, type: :model do end metadata

Slide 199

Slide 199 text

According to type of tests, RSpec will mixin different functionality automagically

Slide 200

Slide 200 text

RSpec.describe User, focus: true do end metadata $ rspec --tag focus only run spec with special tag

Slide 201

Slide 201 text

Rails & Testing

Slide 202

Slide 202 text

RAILS_ENV = test config/environments/test.rb

Slide 203

Slide 203 text

bin/rake db:test:prepare run pending migrations and load schema https://github.com/rails/rails/blob/v4.2.4/activerecord/lib/active_record/railties/databases.rake#L359-L364

Slide 204

Slide 204 text

ActiveSupport::TestCase ActionController::TestCase ActionMailer::TestCase ActionView::TestCase ActiveJob::TestCase ActionDispatch::IntegrationTest Read these API docs on http://api.rubyonrails.org/

Slide 205

Slide 205 text

Fixture

Slide 206

Slide 206 text

Fixture # spec/fixtures/users.yml juanitofatas: name: JuanitoFatas email: [email protected] # spec/rails_helper.rb RSpec.configure do |config| config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = true end # under describe or context users :juanitofatas # => #

Slide 207

Slide 207 text

FactoryGirl A DSL to generate objects

Slide 208

Slide 208 text

# spec/factories/user.rb Factory.define do factory :user do name "Juanito Fatas" email "[email protected]" end end

Slide 209

Slide 209 text

FactoryGirl.attributes_for(:user) # => { name: "JuanitoFatas", email: "[email protected]" }

Slide 210

Slide 210 text

# In spec FactoryGirl.create(:user) FactoryGirl.build(:user) # Map to Active Record User.create(…) User.new(…)

Slide 211

Slide 211 text

gem "factory_girl_rails" bundle mkdir spec/factories *OTUBMM in development and test group

Slide 212

Slide 212 text

spec/factories/*.rb $POWFOUJPO * is respective model name, user.rb

Slide 213

Slide 213 text

RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end $PO H create(:user) instead of FactoryGirl.create(:user) https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

Slide 214

Slide 214 text

Minimum Valid Object 5JQ

Slide 215

Slide 215 text

Types of Test

Slide 216

Slide 216 text

https://robots.thoughtbot.com/rails-test-types-and-the-testing-pyramid

Slide 217

Slide 217 text

https://robots.thoughtbot.com/rails-test-types-and-the-testing-pyramid Bottom Top

Slide 218

Slide 218 text

https://robots.thoughtbot.com/rails-test-types-and-the-testing-pyramid Inside Outside

Slide 219

Slide 219 text

https://robots.thoughtbot.com/rails-test-types-and-the-testing-pyramid User Code

Slide 220

Slide 220 text

https://robots.thoughtbot.com/rails-test-types-and-the-testing-pyramid Coverage

Slide 221

Slide 221 text

https://robots.thoughtbot.com/rails-test-types-and-the-testing-pyramid Fast Slow

Slide 222

Slide 222 text

No content

Slide 223

Slide 223 text

Feature Spec Outside-in, Acceptance / Customer Test, End-to-End, Top down

Slide 224

Slide 224 text

require "rails_helper" spec/features/*_spec.rb $POWFOUJPO

Slide 225

Slide 225 text

( PBM Automate the manual repeated process Browser, check, refresh, repeat

Slide 226

Slide 226 text

Test like how user use it Use real database records Don’t mock or stub objects External Service can stub 5JQ

Slide 227

Slide 227 text

Happy Path for a given feature 5JQ

Slide 228

Slide 228 text

API to interact with Browser ( FN T capybara Version 2.4.0+ is recommended

Slide 229

Slide 229 text

group :development, :test do gem "capybara" end bundle install *OTUBMM

Slide 230

Slide 230 text

require "capybara/rails" # in spec/rails_helper.rb $PO H

Slide 231

Slide 231 text

database_rewinder ( FN T Ensure clean state across tests

Slide 232

Slide 232 text

group :test do gem "database_rewinder" end *OTUBMM

Slide 233

Slide 233 text

RSpec.configure do |config| config.before :suite do DatabaseRewinder.clean_all end config.after :each do DatabaseRewinder.clean end end $PO H

Slide 234

Slide 234 text

background feature scenario given "1*

Slide 235

Slide 235 text

&YBN QMF feature "Auth" do given { ... } background { ... } scenario "show name" do ... end end

Slide 236

Slide 236 text

background feature scenario given before describe it let http://git.io/vGyaV alias alias alias alias "1*

Slide 237

Slide 237 text

RSpec.feature "…" do end Capybara API will be available in here http://www.rubydoc.info/github/jnicklas/capybara/master#The_DSL

Slide 238

Slide 238 text

"1* page visit current_path click_on find fill_in choose check select attach_file https://github.com/jnicklas/capybara#the-dsl

Slide 239

Slide 239 text

3BDL5FTU Fastest No JavaScript Can access within Rack No Server Required

Slide 240

Slide 240 text

&YBN QMF feature "Sign In" do scenario "works" do visit root_path click_on "Sign In" fill_in "login", with: "JuanitoFatas" fill_in "password", with: "1passw0rd" click_on "Sign In" end end

Slide 241

Slide 241 text

&YBN QMF feature "Auth" do scenario "show name" do create(:user, name: "Juan") sign_in_as(user) expect(page).to have_content("Juan") end end

Slide 242

Slide 242 text

&YBN QMF feature "Vote" do scenario "upvote" do create(:user, name: "Juan") sign_in_as(user) expect(page).to have_content("Votes 0") find("upvote").click expect(page).to have_content("Votes 1") end end

Slide 243

Slide 243 text

Drivers

Slide 244

Slide 244 text

% SJWFST Plain Firefox Webkit PhantomJS Rack-Test Selenium Capybara-webkit Poltergeist Single DSL to rule them all

Slide 245

Slide 245 text

RSpec.describe User, js: true do ... end enable javascript_driver #SPX TFS

Slide 246

Slide 246 text

4FMFOJVN Selenium 2.0 Firefox JavaScript Can access Remote API EFGBVMU

Slide 247

Slide 247 text

$BQZCBSB8FCLJU Headless Testing JavaScript Faster than selenium

Slide 248

Slide 248 text

1PMUFSHFJTU Headless Testing JavaScript Can Find JS Error No render engine needed

Slide 249

Slide 249 text

Capybara.default_driver Capybara.javascript_driver $PO H

Slide 250

Slide 250 text

Controller Spec Functional Test

Slide 251

Slide 251 text

require "rails_helper" spec/controllers/*_spec.rb describe "#action" $POWFOUJPO * is respective controller name

Slide 252

Slide 252 text

require "rails_helper" RSpec.describe ShopsController do describe "#index" do ... end describe "#new" do ... end describe "#create" do ... end … $POWFOUJPO

Slide 253

Slide 253 text

describe "#show" do ... end describe "#edit" do ... end describe "#update" do ... end describe "#destroy" do ... end end $POWFOUJPO

Slide 254

Slide 254 text

5JQ Ordering should be the same as your actions in controller index new create show edit update destroy

Slide 255

Slide 255 text

response correct & success redirected right authentications session, flash, cookie render correct template instance variable ( PBM

Slide 256

Slide 256 text

params request response session flash cookie "1* get post patch put head delete ActionController::TestCase

Slide 257

Slide 257 text

expect(response).to render_template(:index) expect(response).to redirect_to(location) expect(response.status).to eq(200) expect(flash[:alert]).to eq I18n.t("failed") "1*

Slide 258

Slide 258 text

Can wrap request in method — abstractions 5JQ def do_request get :show, params end

Slide 259

Slide 259 text

RSpec.describe HomeController do describe "#index" do def do_request get :index end it "works" do do_request expect(response).to be_success end end end JOEFY

Slide 260

Slide 260 text

describe HomeController do describe "#index" do def do_request get :index end it "works" do do_request expect(response).to be_success end end end &YBN QMF same scope

Slide 261

Slide 261 text

RESTful controller spec

Slide 262

Slide 262 text

RSpec.describe ThingsController do end TLFMUPO

Slide 263

Slide 263 text

describe "#index" do def do_request get :index end before { do_request } it { expect(response).to be_success } end JOEFY

Slide 264

Slide 264 text

describe "#new" do def do_request get :new end before { do_request } it { expect(response).to be_success } end OFX

Slide 265

Slide 265 text

describe "#create" do def do_request post :create, thing: params end context "success" do ... end context "failure" do ... end end DSFBUF

Slide 266

Slide 266 text

describe "#show" do let(:thing) { create(:thing) } def do_request get :show, id: thing end before { do_request } it { expect(response).to be_success } end TIPX

Slide 267

Slide 267 text

FEJU describe "#edit" do let(:thing) { create(:thing) } def do_request get :edit, id: thing.id end before { do_request } it { expect(response).to be_success } end

Slide 268

Slide 268 text

describe "#update" do let(:thing) { create(:thing) } def do_request patch :update, id: thing.id, thing: params end before { do_request } context "success" do ... end context "failure" do ... end end VQEBUF

Slide 269

Slide 269 text

describe "#destroy" do let!(:thing) { create(:thing) } def do_request delete :destroy, id: thing.id end it "redirects" do expect { do_request }.to change(Thing, :count).by(-1) expect(response).to redirect_to things_path end end EFTUSPZ

Slide 270

Slide 270 text

5JQ Try to keep the specs shape the same across controllers

Slide 271

Slide 271 text

3BJMT post :show, { id: 1 }, { user_id: 1 }, { notice: "flash message" }

Slide 272

Slide 272 text

3BJMT post :show, { id: 1 }, {}, { notice: "flash message" } params session flash

Slide 273

Slide 273 text

3BJMT post :show, { shop_id: 1 }, {}, { notice: "flash message" } params session flash

Slide 274

Slide 274 text

3BJMT post :show, params: { shop_id: 1 }, session: { user_id: 1 }, flash: { notice: "flash message" } Rails 5 Switch to Keyword Arguments https://github.com/rails/rails/pull/18323

Slide 275

Slide 275 text

5JQ Wrap things in Objects, only test message has been invoked in controller skinny controller

Slide 276

Slide 276 text

describe "#create" do context "success" do it "sent welcome mail" do allow(UserMailer).to receive(:welcome) do_request expect(UserMailer).to have_received(:welcome) end end end &YBN QMF

Slide 277

Slide 277 text

describe "#create" do context "success" do it "sent welcome mail" do allow(Payment).to receive(:charge!) do_request expect(Payment).to have_received(:charge!) end end end

Slide 278

Slide 278 text

Model Spec

Slide 279

Slide 279 text

Test how you tried in rails console ( PBM

Slide 280

Slide 280 text

require "rails_helper" spec/models/*_spec.rb $POWFOUJPO

Slide 281

Slide 281 text

describe User do context "associations" do; end context "validations" do; end describe ".class_method" do; end describe "#instance_method" do; end end $POWFOUJPO

Slide 282

Slide 282 text

Use shoulda to write one-liner spec for associations and validations 5JQ

Slide 283

Slide 283 text

ActiveSupport::TestCase 3BJMT

Slide 284

Slide 284 text

describe User do context "associations" do it { expect(User.new).to have_many(:repos) } end end "TTPDJBUJPO

Slide 285

Slide 285 text

describe User do subject { User.new } context "associations" do it { expect(subject).to have_many(:repos) } end end &YBN QMF Implicit subject

Slide 286

Slide 286 text

describe User do context "associations" do it { is_expected.to have_many(:repos) } end end &YBN QMF

Slide 287

Slide 287 text

describe User do context "associations" do it { is_expected.to validate_presence_of :name } end end 7BMJEBUJPO

Slide 288

Slide 288 text

Post.trending scope :trending, -> { order("upvotes DESC") } describe Post do describe ".trending" do popular = create(:post, upvotes: 42) just_created = create(:post, upvotes: 1) trending_posts = Post.trending expect(trending_posts).to \ eq [popular, just_created] end end

Slide 289

Slide 289 text

Helper Spec

Slide 290

Slide 290 text

( PBM Test the view helper as you expected

Slide 291

Slide 291 text

require "rails_helper" spec/helpers/*_spec.rb $POWFOUJPO

Slide 292

Slide 292 text

require "rails_helper" describe EventsHelper do describe "#linkify_event" do it "works" do expect(linkify_event).to eq "RubyKaigi 11st-13rd Dec, 2015" end end end &YBN QMF

Slide 293

Slide 293 text

require "rails_helper" describe EventsHelper do describe "#linkify_event" do it "works" do expect(linkify_event).to eq "RubyKaigi 11st-13rd Dec, 2015" end end end EventsHelper::LinkifyEvent

Slide 294

Slide 294 text

require "rails_helper" describe EventsHelper do describe "#linkify_event" do it "works" do self expect(linkify_event).to eq "RubyKaigi 11st-13rd Dec, 2015" end end end RSpec::ExampleGroups:: EventsHelper::LinkifyEvent

Slide 295

Slide 295 text

require "rails_helper" describe EventsHelper do describe "#linkify_event" do it "works" do expect(linkify_event).to eq "RubyKaigi 11st-13rd Dec, 2015" end end end

Slide 296

Slide 296 text

Mailer Spec

Slide 297

Slide 297 text

ActionMailer::TestCase ActionMailer::Base.deliveries ActionMailer::MessageDelivery 3BJMT

Slide 298

Slide 298 text

spec/mailers/*_spec.rb $POWFOUJPO

Slide 299

Slide 299 text

email_spec ( FN T Why this not in RSpec?

Slide 300

Slide 300 text

group :test do gem "email_spec" end *OTUBMM

Slide 301

Slide 301 text

# Either in spec/rails_helper.rb or # spec/email_helper.rb require "email_spec" RSpec.configure do |config| config.include EmailSpec::Helpers config.include EmailSpec::Matchers end $PO H

Slide 302

Slide 302 text

reply_to deliver_to deliver_from bcc_to cc_to "1* have_subject have_body_text have_header

Slide 303

Slide 303 text

Sent successfully Sent at correct time Sent to right person Email content ( PBM

Slide 304

Slide 304 text

class UserMailer < ActionMailer::Base def welcome_user(user) @user = user mail( to: @user.email, subject: "Welcome to JollyGoodCode!" ) end end &YBN QMF

Slide 305

Slide 305 text

RSpec.describe UserMailer do describe "#welcome_user" do let(:user) { build_stubbed(:user) } let(:email) { email_for(user) } def email_for(user) UserMailer.welcome_user(user) end it { expect(email).to have_subject "Welcome to JollyGoodCode!" } it { expect(email).to deliver_to user.email } end end &YBN QMF

Slide 306

Slide 306 text

Job Spec

Slide 307

Slide 307 text

Job invokes correct methods ( PBM

Slide 308

Slide 308 text

ActiveJob::TestCase ActiveJob::TestHelper 3BJMT

Slide 309

Slide 309 text

spec/jobs/*_spec.rb $POWFOUJPO

Slide 310

Slide 310 text

it "sync repos" do allow(RepoSync).to receive(:new) RepoSyncJob.perform_now(repo) expect(RepoSync).to have_received(:new) end &YBN QMF Sending right messages

Slide 311

Slide 311 text

it "sync repos" do allow(RepoSync).to receive(:new) RepoSyncJob.perform_now(repo) expect(RepoSync).to have_received(:new) end &YBN QMF Logic should be already tested in RepoSync specs

Slide 312

Slide 312 text

View Spec

Slide 313

Slide 313 text

Request Spec

Slide 314

Slide 314 text

Plain Old Ruby Object

Slide 315

Slide 315 text

Similar to Model Spec without loading Rails

Slide 316

Slide 316 text

Interact with the world

Slide 317

Slide 317 text

Run without network Avoid connectivity issues ( PBM

Slide 318

Slide 318 text

API limit Slower Test relies on internet Service no sandbox mode Service not exist 8 IZ

Slide 319

Slide 319 text

spec/**/*_spec.rb '3 &&% 0 . lib/github_client.rb spec/lib/github_client_spec.rb

Slide 320

Slide 320 text

webmock ( FN T Making real request IS A CRIME

Slide 321

Slide 321 text

group :test do gem "webmock" end *OTUBMM

Slide 322

Slide 322 text

require "webmock/rspec" WebMock.disable_net_connect! (allow_localhost: true) $PO H

Slide 323

Slide 323 text

stub_request( HTTP verb, path ).with( HEADER HASH ).to_return( RESPONSE HASH ) 4UVCCJOH

Slide 324

Slide 324 text

expect(WebMock).to have_requested(…). with(…) 4FUUJOH&YQFDUBUJPOT

Slide 325

Slide 325 text

expect( a_request(…) ).to have_been_made 4FUUJOH&YQFDUBUJPOT

Slide 326

Slide 326 text

VCR ( FN T Record response from real API or service cassettes

Slide 327

Slide 327 text

$ curl File.read Ruby Objects Faking responses

Slide 328

Slide 328 text

it "webmock example" do url = "https://api.github.com/users/juanitofatas" fixture = "spec/fixtures/github/juanitofatas.json" # stub_request(:get, url). to_return(body: File.read(fixture)) HTTP.get(url) expect(WebMock).to have_requested(:get, url) expect(a_request(:get, url)).to have_been_made end &YBN QMF

Slide 329

Slide 329 text

&YBN QMF

Slide 330

Slide 330 text

it "webmock example" do url = "https://api.github.com/users/juanitofatas" fixture = "spec/fixtures/github/juanitofatas.json" stub_request(:get, url). to_return(body: File.read(fixture)) HTTP.get(url) expect(WebMock).to have_requested(:get, url) expect(a_request(:get, url)).to have_been_made end &YBN QMF

Slide 331

Slide 331 text

it "webmock example" do url = "https://api.github.com/users/juanitofatas" fixture = "spec/fixtures/github/juanitofatas.json" stub_request(:get, url). to_return(body: File.read(fixture)) HTTP.get(url) expect(WebMock).to have_requested(:get, url) expect(a_request(:get, url)).to have_been_made end &YBN QMF

Slide 332

Slide 332 text

it "webmock example" do url = "https://api.github.com/users/juanitofatas" fixture = "spec/fixtures/github/juanitofatas.json" stub_request(:get, url). to_return(body: File.read(fixture)) HTTP.get(url) expect(WebMock).to have_requested(:get, url) expect(a_request(:get, url)).to have_been_made end &YBN QMF

Slide 333

Slide 333 text

it "webmock example" do url = "https://api.github.com/users/juanitofatas" fixture = "spec/fixtures/github/juanitofatas.json" stub_request(:get, url). to_return(body: File.read(fixture)) HTTP.get(url) expect(WebMock).to have_requested(:get, url) expect(a_request(:get, url)).to have_been_made end &YBN QMF

Slide 334

Slide 334 text

it "webmock example" do url = "https://api.github.com/users/juanitofatas" fixture = "spec/fixtures/github/juanitofatas.json" stub_request(:get, url). to_return(body: File.read(fixture)) HTTP.get(url) expect(WebMock).to have_requested(:get, url) expect(a_request(:get, url)).to have_been_made end &YBN QMF https://github.com/sferik/t

Slide 335

Slide 335 text

&YBN QMF many stub_request examples sferik/t

Slide 336

Slide 336 text

Debugging

Slide 337

Slide 337 text

stop spring pry-rails + binding.pry byebug everywhere p + puts + pp + raise

Slide 338

Slide 338 text

Closing

Slide 339

Slide 339 text

Routing, Request, View Specs Page Object (Feature Spec) Front-end Testing Infrastructure Testing A/B Testing Smoke Testing (example)

Slide 340

Slide 340 text

Routing Specs Request Specs View Specs Page Object (Feature Spec) Front-end Testing Infrastructure Testing A/B Testing Smoke Testing (example) NOT COVERED

Slide 341

Slide 341 text

LEGACY CODE

Slide 342

Slide 342 text

Skip Pending v.s. not run at all run but won’t failed

Slide 343

Slide 343 text

1. Write Feature Spec 2. New things with specs 3. Use Exception monitoring service

Slide 344

Slide 344 text

1. Write Feature Spec 2. New things with specs 3. Use Exception monitoring service 4. Find another job

Slide 345

Slide 345 text

DON’T TEST private Method test the method which uses it

Slide 346

Slide 346 text

Wrap Everything in objects so much easier to test

Slide 347

Slide 347 text

Use shoulda to simplify when you get tired.

Slide 348

Slide 348 text

Use tools to simplify when you get tired.

Slide 349

Slide 349 text

Don’t aim for 100% test coverage

Slide 350

Slide 350 text

I get paid for code that works, so my philosophy is to test as little as possible to reach a given level of confidence.— Kent Back “

Slide 351

Slide 351 text

We read more than we write

Slide 352

Slide 352 text

Anything that can go wrong, will go wrong

Slide 353

Slide 353 text

That’s why we write tests

Slide 354

Slide 354 text

Tests are also code. Will become stinky, break up when it’s time

Slide 355

Slide 355 text

There are million ways of how things are tested

Slide 356

Slide 356 text

There’s no tomorrow.

Slide 357

Slide 357 text

WRITE TEST NOW

Slide 358

Slide 358 text

A test is better than no test

Slide 359

Slide 359 text

Feature Model Controller

Slide 360

Slide 360 text

Do Code Review

Slide 361

Slide 361 text

Team Style Guide

Slide 362

Slide 362 text

Takeaways

Slide 363

Slide 363 text

ALWAYS BE TESTING

Slide 364

Slide 364 text

Resource

Slide 365

Slide 365 text

Talks

Slide 366

Slide 366 text

https://www.youtube.com/watch?v=MA4jJNUG_dI

Slide 367

Slide 367 text

http://git.io/vsOKE

Slide 368

Slide 368 text

https://www.youtube.com/watch?v=Libc0-0TRg4

Slide 369

Slide 369 text

Books

Slide 370

Slide 370 text

No content

Slide 371

Slide 371 text

https://leanpub.com/rspecbook RUBYCONFTW2015 ⯜顤 8 PSL*O1SPHSFTT IPROMISEYOUIWILLWRITETESTS ! ✿䫓 ! 45RGE⑆桡⻇㔑 D[,WCPKVQ(CVCU

Slide 372

Slide 372 text

Talk to me! I’m happy to help you

Slide 373

Slide 373 text

6JCPM[QW HQT.KUVGPKPI

Slide 374

Slide 374 text

6GC6KOG ☕

Slide 375

Slide 375 text

No content