Rspec Rake 任务:如何解析参数? [英] Rspec Rake Task: How to parse a parameter?

查看:29
本文介绍了Rspec Rake 任务:如何解析参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a rake task which generates a new User. Values of email, password and password_confirmation (confirm) needs to be typed in through the command line.

这是我的佣金任务代码:

This is my rake task code:

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"来调用它.

I can call this by typing "rake db:setup:admin" from my command line.

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

Now I want to test this task with a rspec. So far I managed to create the following spec file:

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 任务不会要求这些字段的值.

While running the specs the of my rake task will ask for input from my command line. So what I need is to parse a value for email, password and confirm so that when executing my specs the rake task won't ask for a value of those fields.

如何从规范文件中实现这一点?

How can I achieve this from the spec file?

推荐答案

你可以去掉 HighLine:

describe "rake task setup:admin" do
  let(:highline){ double(:highline) }
  let(:email){ "test@example.com" }
  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

这篇关于Rspec Rake 任务:如何解析参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆