存根命令行结果 rspec

stub commandline result in rspec

我以前从未使用过ruby和rspec。

我写了几行代码,用户可以从他们的 mac 中删除钥匙串。

    elsif params[:name]
  # get default keychains list
  default_path = Fastlane::Actions.sh("security list-keychains", log: false).split

  # iterate to find any of the items in the list matches with parameter name
  does_keychain_exists = true
  default_path.each do |path_to_keychain|
    # sometimes keychain saved as name.keychain-db, check that case too
    if path_to_keychain.include?(params[:name]) == true || path_to_keychain.include?("#{params[:name]}-db") == true
      keychain_path = FastlaneCore::Helper.keychain_path(params[:name])
      if File.exist?(keychain_path)
        complete_delete(original, keychain_path)
      else
        does_keychain_exists = false
      end
    else
      does_keychain_exists = false
    end
  end

代码运行良好,但我需要使用 rspec 添加单元测试。

我如何存根 default_path = Fastlane::Actions.sh("security list-keychains", log: false).split 以便 default_path 变量得到类似

的东西

~/Library/Keychains/test.keychainuser/username/Library/Keychains/test.keychain

我要编辑的单元测试是:

  describe Fastlane do
  describe Fastlane::FastFile do
    describe "Delete keychain Integration" do
      before :each do
        allow(File).to receive(:file?).and_return(false)
      end

      it "works with keychain name found locally" do
        allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(nil)
        keychain = File.expand_path('test.keychain')
        allow(File).to receive(:file?).and_return(false)
        allow(File).to receive(:file?).with(keychain).and_return(true)

        result = Fastlane::FastFile.new.parse("lane :test do
          delete_keychain ({
            name: 'test.keychain',
            throw_error:false
          })
        end").runner.execute(:test)

        expect(result).to eq("security delete-keychain #{keychain}")
      end

你可以这样做:

keychains = double("keychains")
allow(keychains).to receive(:split).and_return(["~/Library/Keychains/test.keychain", "user/username/Library/Keychains/test.keychain"]
allow(Fastlane::Actions).to receive(:sh).with("security list-keychains", log: false)).and_return(keychains)