jeudi 21 janvier 2016

Rspec Rake Task: How to parse a parameter?

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"].invoke(email: "hi")
  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?

Aucun commentaire:

Enregistrer un commentaire