You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RSpec中对Fastlane::Actions.sh打桩测试Mac钥匙串删除逻辑

给Fastlane的security list-keychains调用打RSpec桩的方法

没问题!我来帮你搞定这个RSpec打桩的事儿~ 核心思路就是模拟Fastlane::Actions.sh方法的返回值,让它在收到特定参数时返回我们预设的钥匙串路径字符串,这样split后就能得到你想要的default_path数组。

具体实现步骤

假设你的业务代码是类似这样的(放在某个类或方法里):

def get_default_keychains
  default_path = Fastlane::Actions.sh("security list-keychains", log: false).split
  # 后续处理逻辑...
end

对应的RSpec测试可以这么写:

describe "你的类/方法名称" do
  it "正确获取模拟的钥匙串路径" do
    # 第一步:预设模拟的命令输出
    # 注意:要和`security list-keychains`的真实输出格式匹配(通常是带双引号、空格分隔的路径)
    stubbed_output = '"/Users/username/Library/Keychains/test.keychain" "~/Library/Keychains/another.keychain"'

    # 第二步:给Fastlane::Actions.sh打桩
    # 指定当调用参数为"security list-keychains"且log: false时,返回我们预设的字符串
    allow(Fastlane::Actions).to receive(:sh)
      .with("security list-keychains", log: false)
      .and_return(stubbed_output)

    # 第三步:执行你的业务方法
    result = get_default_keychains

    # 第四步:验证结果是否符合预期
    # 如果你的代码没处理引号,结果会带双引号;如果处理了(比如gsub(/"/, '')),就写不带引号的路径
    expect(result).to eq([
      "/Users/username/Library/Keychains/test.keychain",
      "~/Library/Keychains/another.keychain"
    ])
  end

  # 如果你需要测试单个钥匙串的场景
  it "处理单个模拟钥匙串路径" do
    stubbed_output = '"~/Library/Keychains/test.keychain"'
    allow(Fastlane::Actions).to receive(:sh)
      .with("security list-keychains", log: false)
      .and_return(stubbed_output)

    result = get_default_keychains
    expect(result).to eq(["~/Library/Keychains/test.keychain"])
  end
end

关键细节说明

  1. 匹配真实输出格式:security list-keychains的实际输出会用双引号包裹每个路径,并用空格分隔。所以你的stub字符串要和这个格式一致,这样split后才能得到正确的元素(如果你的代码后续会去掉引号,记得在测试验证时对应调整)。
  2. 精准匹配参数:打桩时一定要明确指定with("security list-keychains", log: false),避免影响其他地方对Fastlane::Actions.sh的调用。
  3. 验证调用(可选):如果你想确保这个sh命令确实被调用了,可以在测试末尾加上:
    expect(Fastlane::Actions).to have_received(:sh).with("security list-keychains", log: false)
    

内容的提问来源于stack exchange,提问作者SpaceDust__

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:11:21