Rspec Rake Task: How to parse a parameter?

2019-05-17 18:11发布

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

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

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

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?

1条回答
我想做一个坏孩纸
2楼-- · 2019-05-17 18:31

You could stub out 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
查看更多
登录 后发表回答