解释如何对 Ruby 写的链码做单元测试

解读

在国内 Hyperledger Fabric 项目里,链码(Chaincode) 通常用 Go 或 Node.js 编写,但官方从 2.x 开始支持 Ruby shim。
面试官问“Ruby 写的链码如何单元测试”,核心想确认三件事:

  1. 你是否真的用 Ruby 写过链码,而不是只会 Rails;
  2. 是否理解链码的运行时约束(无全局状态、依赖 gRPC、stub 接口);
  3. 能否在不启 peer 节点、不打包 Docker 镜像的前提下,把业务逻辑测到 80% 以上覆盖率,并持续集成到 GitLab-CI 或 GitHub Actions。

知识点

  1. fabric-contract-api-rb 与 fabric-shim 的接口模型:必须继承 Contract 基类,入口函数签名固定为 def my_function(ctx, arg1, arg2),其中 ctx 是 TransactionContext。
  2. stub 对象:ctx.stub 提供 getState、putState、deleteState、getStateByRange、getTxTimestamp 等底层方法;单元测试必须 mock 这些调用。
  3. 最小化可测单元:把“链码类”拆成两层——纯领域模型(PORO)与 Contract 壳。前者不含任何 ctx.stub,可完全脱离 Fabric 运行;后者只做参数校验和 stub 调用,逻辑极薄,基本不用测。
  4. Mock 框架选型:国内团队主流用 RSpec 3.x + instance_double;若追求速度,可用 Minitest + flexmock;务必把 fabric-shim 的类打桩(stub_const),否则 gem 会尝试加载 gRPC 原生扩展,CI 镜像里经常缺 libgrpc-dev 导致失败。
  5. 覆盖率门禁:国企/金融客户通常要求 SimpleCov 90% 以上,并在合并请求里自动上传报告到 SonarQube 社区版。
  6. CI 流水线:GitLab-CI 用 ruby:3.2-slim 镜像,阶段顺序是 bundle install → rubocop → rspec → simplecov → sonar-scanner;若用 GitHub Actions,需缓存 vendor/bundle,否则每次拉取 grpc 会超时。

答案

下面给出一套可直接落地的 RSpec 最小范例,覆盖 新增资产 与 查询资产 两个方法,全部在内存里完成,无需启动 peer。

# contract/asset_contract.rb
require 'fabric/contract'

class AssetContract < Fabric::Contract
  def create_asset(ctx, id, color, size, owner, appraised_value)
    raise 'asset already exists' if ctx.stub.get_state(id).present?

    asset = {
      ID:             id,
      Color:          color,
      Size:           size.to_i,
      Owner:          owner,
      AppraisedValue: appraised_value.to_i
    }
    ctx.stub.put_state(id, JSON.generate(asset))
  end

  def read_asset(ctx, id)
    bytes = ctx.stub.get_state(id)
    raise 'asset not found' if bytes.nil? || bytes.empty?

    JSON.parse(bytes, symbolize_names: true)
  end
end
# spec/asset_contract_spec.rb
require 'rails_helper' # 或 require 'spec_helper'
require 'fabric/contract_context'
require 'json'

RSpec.describe AssetContract, type: :contract do
  let(:stub)   { instance_double('Fabric::Stub') }
  let(:ctx)    { Fabric::ContractContext.new(stub) }
  let(:contract) { described_class.new }

  describe '#create_asset' do
    it 'persists a new asset' do
      expect(stub).to receive(:get_state).with('asset1').and_return('')
      expect(stub).to receive(:put_state).with('asset1', anything) do |_key, json|
        data = JSON.parse(json, symbolize_names: true)
        expect(data[:Color]).to eq('red')
      end
      contract.create_asset(ctx, 'asset1', 'red', '10', 'tom', '888')
    end

    it 'raises when duplicate' do
      expect(stub).to receive(:get_state).with('asset1').and_return('exists')
      expect { contract.create_asset(ctx, 'asset1', 'red', '10', 'tom', '888') }
        .to raise_error(/already exists/)
    end
  end

  describe '#read_asset' do
    it 'returns asset json' do
      payload = { ID: 'asset1', Color: 'red' }.to_json
      expect(stub).to receive(:get_state).with('asset1').and_return(payload)
      result = contract.read_asset(ctx, 'asset1')
      expect(result[:Color]).to eq('red')
    end

    it 'raises when not found' do
      expect(stub).to receive(:get_state).with('asset1').and_return(nil)
      expect { contract.read_asset(ctx, 'asset1') }.to raise_error(/not found/)
    end
  end
end

运行命令

bundle exec rspec --format documentation  
open coverage/index.html   # 确认 100% 覆盖

关键说明

  1. 用 instance_double('Fabric::Stub') 而不是 double,保证方法名拼写错误会立即失败;
  2. 把 ContractContext 做成薄包装,内部只含 stub 属性,方便注入;
  3. 所有 JSON 序列化都显式调用 JSON.generate/parse,避免链码与客户端因格式差异导致 state hash 不一致;
  4. 若链码里用到 getStateByRange 等迭代器,可 mock 返回 Fabric::StateQueryIterator.new([...]),同样无需真数据库;
  5. 在 spec/spec_helper.rb 里加 SimpleCov.start { add_filter '/spec/' },并设置 minimum_coverage 90,CI 不达标即失败,符合国内金融交付要求。

拓展思考

  1. 集成测试怎么补:单元测试只能保证逻辑正确,State-based 背书策略、链码事件抛出、私有数据集合(PDC) 仍需在 Fabric Test Network 里跑。推荐用 fabric-sdk-ruby 的 Gateway 类,在 GitLab-CI 里启动 cryptogen 与 peer 容器,跑 3~5 个关键场景即可,时间控制在 5 分钟以内。
  2. 性能基线:国企招标常要求 TPS ≥ 300。可在单元测试层用 benchmark-ips 给纯领域逻辑打基准;真正的吞吐瓶颈在 I/O,与 Ruby 无关,提前准备数据可在答辩时加分。
  3. 链码升级兼容性:如果同一通道已存在旧版链码,新增字段必须 JSON.parse 后做 backward-compatible 处理,单元测试里需补 version migration 场景,否则升级提案会失败。
  4. 安全左移:把 rubocop-performance、brakeman、bundle-audit 全加到 pre-commit 钩子,国内银行客户审计时直接看 .gitlab-ci.yml 就能给安全分,减少反复补报告。