exapmpleグループを作成するためにはdescribe
とit
はexampleを宣言する(文脈を作成)する
Basic Structure
RSpecはdescribe
とit
の言葉を使うので会話のような構想で表現できます
RSpec uses the words "describe" and "it" so we can express concepts like a conversation:
"Describe an order."
"It sums the prices of its line items."
RSpec.describe Order do
it "sums the prices of its line items" do
order = Order.new
order.add_entry(LineItem.new(:item => Item.new(
:price => Money.new(1.11, :USD)
)))
order.add_entry(LineItem.new(:item => Item.new(
:price => Money.new(2.22, :USD),
:quantity => 2
)))
expect(order.total).to eq(Money.new(5.55, :USD))
end
end
describe
メソッドはexampleグループを作成する。describe
へ渡されるブロック内はit
メソッドを使ってexampleを宣言できる
The describe method creates an ExampleGroup. Within the block passed to describe you can declare examples using the it method.
内部的には、exampleグループはdescribe
へ渡されるブロックは検査されるクラスです。it
へ渡されるブロックはそのクラスのインスタンスの文脈内で検査される。
Under the hood, an example group is a class in which the block passed to describe is evaluated. The blocks passed to it are evaluated in the context of an instance of that class.
describe
かcontext
で入れ子のグループを宣言できる
入れ子グループ
Nested Groups
describe
かcontext
を使って入れ子グループを宣言もできます
You can also declare nested groups using the describe or context methods:
RSpec.describe Order do
context "with no items" do
it "behaves one way" do
# ...
end
end
context "with one item" do
it "behaves another way" do
# ...
end
end
end
入れ子グループは外側のexampleグループクラスのサブクラスであり、あなたが望む継承セマンティックスを無料で供給します
Nested groups are subclasses of the outer example group class, providing the inheritance semantics you'd want for free.
セマンティックス
exampleのcontext
は状況ごとに使う
エイリアス
Aliases
describe
またはcontext
のどちらか一方を使ってexampleグループを宣言できる。トップレベルexampleグループに対して、describe
とcontext
はRSpecから使用可能です。前後の互換性に対しては、モンキーパッチが使用不可でない場合、mainオブジェクトとモジュールからも使用可能です。
You can declare example groups using either describe or context. For a top level example group, describe and context are available off of RSpec. For backwards compatibility, they are also available off of the main object and Module unless you disable monkey patching.
it
、specify
、example
のいずれかを使ってグループ内でexampleを宣言できます。
You can declare examples within a group using any of it, specify, or example.
条件別で使う
context で条件別にグループ化する
RSpecには describe 以外にも context という機能でテストをグループ化することもできます。
どちらも機能的には同じですが、 context は条件を分けたりするときに使うことが多いです。
ちなみに、contextは日本語で「文脈」や「状況」の意味になります。ここでは「12歳以下の場合」と「13歳以上の場合」という二つの条件にグループ分けしてみました。