Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
外部APIが絡むテストをちょっといい感じに書く/a-little-nice-writing-e...
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Masatoshi Moritsuka
February 26, 2025
Programming
43
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
外部APIが絡むテストをちょっといい感じに書く/a-little-nice-writing-external-api-testing
Masatoshi Moritsuka
February 26, 2025
Transcript
29 slides
外部API が絡む テストを ちょっといい感じに 書く 森塚 真年(@sanfrecce_osaka) 2025/02/26 Kyobashi.rb#5 #kyobashirb
自己紹介 森塚 真年 GitHub: @sanfrecce-osaka Twitter(X) ・Qiita: @sanfrecce_osaka 趣味: コミュニティ・勉強会
Machida.rb(next: 2/7( 金)) Hirakata.rb(next: 1/26( 日)) 株式会社GMO エンペイ Ruby3.3.6/Rails7.1( 次は3 月末までに 7.2 に上げ るぞ) Node.js v18/Vue.js 3.3/Vuetify 3.4
本編
外部API 絡むテスト
どのように 書いてますか?
stub_request(:post, 'https://example.com/') .to_return_json(body: { id: 1, foo: 'bar', baz: true
})
1 箇所だけなら まだいいけど…
stub_request(:post, 'https://example.com/') .to_return_json(body: { id: 1, foo: 'bar', baz: true
}) # ... stub_request(:post, 'https://example.com/') .to_return_json(body: { id: 1, foo: 'piyo', baz: true }) # ... stub_request(:post, 'https://example.com/') .to_return_json(body: { id: 1, foo: 'bar', baz: false }) .to_return_json(body: { error_code: 'EE01' })
つらい😇
中には
レスポンスが JSON じゃない API
stub_request(:post, 'https://example.com/') .to_return(body: URI.encode_www_form( ID: 1, Foo: 'bar', Baz #
... stub_request(:post, 'https://example.com/') .to_return(body: URI.encode_www_form( ID: 1, Foo: 'piyo', Ba # ... stub_request(:post, 'https://example.com/') .to_return(body: URI.encode_www_form( ID: 1, Foo: 'bar', Baz .to_return(body: URI.encode_www_form( ErrorCode: 'EE01' ))
つらい😇
そこで
FactoryBot
FactoryBot.define do factory :foo_bar_response, class: Hash do id { 1
} foo { 'bar' } bar { true } initialize_with { attributes.stringify_keys } end end
FactoryBot.define do factory :foo_bar_response, class: Hash, traits: %i[success] trait :success
do id { 1 } foo { 'bar' } bar { true } end trait :error do transient do id { nil } foo { nil } bar { nil } end
stub_request(:post, 'https://example.com/') .to_return_json(body: build(:foo_bar_response)) # ... stub_request(:post, 'https://example.com/') .to_return_json(body: build(:foo_bar_response,
foo: 'piyo' } # ... stub_request(:post, 'https://example.com/') .to_return_json(body: build(:foo_bar_response, baz: false }) .to_return_json(body: build(:foo_bar_response, :error, error
FactoryBot.define do factory :foo_bar_response, class: 'String', traits: %i[succe trait :success
do self.ID { 1 } self.Foo { 'bar' } self.Bar { true } end trait :error do transient do self.ID { nil } self.Foo { nil } self.Bar { nil } end
stub_request(:post, 'https://example.com/') .to_return(body: build(:foo_bar_response)) # ... stub_request(:post, 'https://example.com/') .to_return(body: build(:foo_bar_response,
Foo: 'piyo' }) # ... stub_request(:post, 'https://example.com/') .to_return(body: build(:foo_bar_response, Baz: false }) .to_return(body: build(:foo_bar_response, :error, ErrorCode:
文字列じゃなくて Hash が欲しい場合 attributes_for(:foo_bar_response) => { ID: id, Foo: foo,
Bar:
module ExternalApiStubHelper module Hoge module Fuga def mock_hoge_fuga(stub_hoge_fuga: nil, hoge_fuga_respon
hoge_fuga_request = stub_request(:post, 'https://examp stub_hoge_fuga ? stub_hoge_fuga.call(hoge_fuga_request end end end end
# frozen_string_literal: true module ExternalApiStubHelper include Hoge end
vcr
こんなことない? 外部に実際にリクエストしていて CI が遅い どこで呼ばれているかわからない外部 API のリク エスト 最近見つけたやつ: カード情報を消すための
trait
RSpec.describe 'Foo', type: :request do # ちょっとでも外部の API 叩くなら vcr
を true にする # WebMock で stub する前提でもとりあえず true にする describe 'GET xxx', vcr: true do # ... end end
VCR.configure do |c| # ... c.default_cassette_options = { # CI
では cassette を生成しないようにする record: ENV['CI'] ? :none : :new_episodes, # ... } end
ご清聴 ありがとうございました。
None
More Decks by Masatoshi Moritsuka
See All by Masatoshi Moritsuka
拙者、『型は欲しいが型は書きたくない』者たちとの和睦を結び、るびぃにおける型の領地安堵を実現せんと欲す者也 #sekigahara01/sekigahara01
sanfrecce_osaka
4
2.8k
Rails の CLI ツールの書き方/writing-rails-cli-tool
sanfrecce_osaka
0
93
Time.zone.parse('dark')/time-zone-parse-dark
sanfrecce_osaka
0
150
gem_rbs_collection へのコントリビュートから始める Ruby の型の世界/contributing-gem-rbs-collection
sanfrecce_osaka
0
690
Rails と人魚の話/rails-and-mermaid
sanfrecce_osaka
0
520
パターンマッチ使ってるかい?(kyobashi.rb)/use-ruby-s-pattern-matching-on-kyobashi-rb
sanfrecce_osaka
0
320
ApplicationController の継承を分割してエラーを減らした話/dividing-application-controller
sanfrecce_osaka
1
460
Input object ではじめる入力値検証/input-value-validation-using-input-object
sanfrecce_osaka
0
640
実例で学ぶRailsアプリケーションデバッグ入門 〜ログインできちゃってました編〜/rails-application-debug-introduction
sanfrecce_osaka
2
960
Other Decks in Programming
See All in Programming
AI-Powered Domain-Driven Design
ziobrando
0
440
現場と育てるRailsモデリング 〜Spreadsheetから始めたモデル設計〜
siroemk
2
1.2k
protojson における文字化けの扱い
kazuki1023
0
410
ローカルLLMの基本と近況 2611 / Local LLM basics and recent situation 2611
kishida
1
250
Next.js: The final boss of Web Performance
guaca
0
400
Lambda durable functionsでHuman in the Loopを楽に…楽に……
har1101
2
310
SFCで実現する病院・医療システムの動的組み立て式UI
koukimiura
1
180
例外からRich Errorsまで Kotlinエラーハンドリングの進化を読み解く
shiita0903
0
120
作れるエンジニアから、価値を届けるエンジニアへ
ryunakayama
1
280
止まらない比較を止める — 余帰納法で無限ストリームを比べる
tarao
0
140
TS 7.0 で baseUrl が使えなくなった今、パスエイリアスをどうするか
bicstone
2
640
AI Augmentation Techniques with Liberty
ivargrimstad
1
470
Featured
See All Featured
Imperfection Machines: The Place of Print at Facebook
scottboms
270
14k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.6k
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
Practical Orchestrator
shlominoach
192
12k
A better future with KSS
kneath
240
18k
[RailsConf 2023] Rails as a piece of cake
palkan
59
7.1k
Accessibility Awareness
sabderemane
1
300
Rails Girls Zürich Keynote
gr2m
96
14k
Agile Leadership in an Agile Organization
kimpetersen
PRO
0
310
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
162
16k
Code Review Best Practice
trishagee
74
20k
Public Speaking Without Barfing On Your Shoes - THAT 2023
reverentgeek
1
660