【问题标题】:stub commandline result in rspec存根命令行导致 rspec
【发布时间】:2018-02-13 16:07:24
【问题描述】:

我以前从未使用过 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 添加 unittest。

我如何存根 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

【问题讨论】:

  • Fastlane::Actions.expects(:sh).with("security list-keychains", log: false).returns("~/Library/Keychains/test.keychain user/username/Library/Keychains/test.keychain") 这行得通吗?

标签: ruby unit-testing command-line rspec keychain


【解决方案1】:

你可以这样做:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 2021-02-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多