diffを生成するときに使用される方法expected
とactual
を無効にすることができます。この例では、インスタンス変数として期待値と実際の値を格納し、インスタンス変数を返すメソッドを定義:
RSpec::Matchers.define :be_matching_content do |expected_raw|
match do |actual_raw|
@actual = actual_raw.gsub(/\s/,'')
@expected = expected_raw.gsub(/\s/,'')
expect(expected).to eq(@actual)
end
diffable
attr_reader :actual, :expected
end
別の例オブジェクトの二つの異なるタイプの特定の属性の一致することです。 (この場合の予想されるオブジェクトはClient
モデルです。)
RSpec::Matchers.define :have_attributes_of_v1_client do |expected_client|
match do |actual_object|
@expected = client_attributes(expected_client)
@actual = actual_object.attributes
expect(actual_object).to have_attributes(@expected)
end
diffable
attr_reader :actual, :expected
def failure_message
"expected attributes of a V1 Client view row, but they do not match"
end
def client_attributes(client)
{
"id" => client.id,
"client_type" => client.client_type.name,
"username" => client.username,
"active" => client.active?,
}
end
end
例の障害は次のようになります。
Failure/Error: is_expected.to have_attributes_of_v1_client(client_active_partner)
expected attributes of a V1 Client view row, but they do not match
Diff:
@@ -1,6 +1,6 @@
"active" => true,
-"client_type" => #<ClientType id: 2, name: "ContentPartner">,
+"client_type" => "ContentPartner",
"id" => 11,
注これは、唯一のバージョン3.4から始まるRSpecのドキュメントに記載されています。また、ドキュメントによれば、インスタンス変数名として '@ actual'を使用する場合、' attr_reader'は必要ありません。 –