SpecFormula AI
ISA後端符號系統

VAR-System

變數擷取、儲存與引用

VAR-System 讓你在測試步驟間傳遞動態產生的值,如資料庫自動產生的 ID 或 API 回應中的 Token。

四種語法

語法名稱位置用途
>contextKeyContext KeyDataTable 標頭定義變數名稱
<executionKeyExecution KeyDataTable 資料指定擷取的欄位
$variableVariable Reference任何值的位置引用變數(保留型別)
${variable}String Interpolation字串中嵌入變數(轉為字串)

擷取變數

使用 >< 配對,從執行結果中擷取值:

When 創建使用者, call table:
  | >userId | >userToken | name  | email             |
  | <id     | <token     | Alice | alice@example.com |

執行後:

  • userId = 回應中的 id 欄位值
  • userToken = 回應中的 token 欄位值

引用變數

$variable(型別保留)

Then 驗證使用者存在, with:
  | id      | name  |
  | $userId | Alice |

$userId 保留原始型別(Integer、String 等)。

${variable}(轉為字串)

When 批量查詢, call table:
  | ids                       |
  | ${user1.id},${user2.id}   |

${...} 會將值轉為字串,適合組合多個變數。

$var vs ${var}

面向$variable${variable}
使用場景整個值即為變數嵌入字串中
型別保留原始型別轉為 String
多變數組合不支援支援
範例$userId12345"ID: ${userId}""ID: 12345"

巢狀路徑

支援 dot notation 和陣列索引:

# 物件巢狀
| >orderId           |
| <order.details.id  |

# 陣列索引
| >firstItem     |
| <items[0].name |

配對規則

>< 必須在同一欄位中配對:

Header:  | >contextKey | normalField | >anotherKey |
Data:    | <fieldName  | normalData  | <otherField |
         ↑ 配對         ↑ 非配對       ↑ 配對

重複 Context Key:若多個步驟使用相同的 >contextKey,Lint 會發出警告。框架執行時後者會覆蓋前者的值。

引號規則

  • DataTable 中被引號包裹時不解析"$var" 視為純字串
  • JSON DocString 中變數不可放在 "",否則視為純字串:
# ✅ 正確:符號在引號外
"""json
{ "userId": $userId }
"""

# ❌ 錯誤:符號被引號包裹,視為純字串
"""json
{ "userId": "$userId" }
"""

邊界行為

Null 處理

# 執行結果為 null → 存入 ScenarioContext 為 null
| >agentId |
| <id      |  # id 為 null → agentId = null

# 變數未找到 → 回傳原始字串
| $undefinedVar |  # → 字串 "$undefinedVar"

字串內插邊界

# 未關閉的括號 → 保留原文
| User ${name without closing |  # → "User ${name without closing"

# 變數不存在 → 保留原文
| User ${notFound} |  # → "User ${notFound}"

保留字

now 是保留字,不可作為 Context Key:

# ❌ 錯誤
| >now |

完整範例

Feature: 變數傳遞

  Example: 建立使用者後查詢
    # 1. 擷取使用者 ID
    When (No Actor) 建立使用者, call table:
      | >user1.id | name  | email             |
      | <userId   | Alice | alice@example.com |

    # 2. 使用變數查詢
    When (UID="$user1.id") 查詢個人資料, call table:
      | |
    Then 查詢個人資料(200)回應, with table:
      | userId     | name  |
      | $user1.id  | Alice |

    # 3. 字串內插用於批量查詢
    When (No Actor) 建立使用者, call table:
      | >user2.id | name | email           |
      | <userId   | Bob  | bob@example.com |
    When (No Actor) 批量查詢使用者, call table:
      | Q:userIds                   |
      | ${user1.id},${user2.id}     |

目錄