我有一个生成新用户的rake任务。需要通过命令行输入email,password和password_confirmation(confirm)的值。
这是我的佣金任务代码:
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任务不会要求这些字段的值。
如何从spec文件中实现此目的?
答案 0 :(得分:2)
你可以找出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