Rspec Rake任务:如何解析参数?

克里斯·克

我有一个rake任务,它会生成一个新用户。email,password和password_confirmation(确认)的值需要通过命令行输入。

这是我的瑞克任务代码:

namespace :db do
  namespace :setup do
    desc "Create Admin User"
    task :admin => :environment do
      ui       = HighLine.new      
      email    = ui.ask("Email: ")
      password = ui.ask("Enter password: ") { |q| q.echo = false }
      confirm  = ui.ask("Confirm password: ") { |q| q.echo = false }

      user = User.new(email: email, password: password,
                  password_confirmation: confirm)
      if user.save
        puts "User account created."
      else
        puts
        puts "Problem creating user account:"
        puts user.errors.full_messages
      end
    end
  end
end

我可以通过在命令行中键入“ rake db:setup:admin”来调用它。

现在,我想使用rspec测试此任务。到目前为止,我设法创建了以下规范文件:

require 'spec_helper'
require 'rake'

describe "rake task setup:admin" do 
  before do
    load File.expand_path("../../../lib/tasks/setup.rake", __FILE__)
    Rake::Task.define_task(:environment)
  end

  let :run_rake_task do 
    Rake.application["db:setup:admin"]
  end

  it "creates a new User" do
    run_rake_task
  end
end

在运行规范时,我的rake任务的要求从命令行输入。因此,我需要解析电子邮件,密码值并确认,以便在执行我的规格时,rake任务不会要求这些字段的值。

如何从规格文件中实现?

鲁伊·迪亚兹(Ruy Diaz)

您可以存根HighLine

describe "rake task setup:admin" do
  let(:highline){ double(:highline) }
  let(:email){ "[email protected]" }
  let(:password){ "password" }

  before do
    load File.expand_path("../../../lib/tasks/setup.rake", __FILE__)
    Rake::Task.define_task(:environment)
    allow(HighlLine).to receive(:new).and_return(highline)
    allow(highline).to receive(:ask).with("Email: ").and_return(email)
    allow(highline).to receive(:ask).with("Enter password: ").and_return(password)
    allow(highline).to receive(:ask).with("Confirm password: ").and_return(password)
  end

  let :run_rake_task do
    Rake.application["db:setup:admin"]
  end

  it "creates a new User" do
    run_rake_task
  end
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章