2017-03-07 58 views
-1

我有一个项目来创建模板ruby项目。如何在Serverspec/RSpec测试中调用bundler命令

我正在使用serverspec并希望验证模板的行为。

但是,使用command(`rake -T`)失败。如果我手动执行该命令,它按预期工作。

调试,当测试在Serverspec运行时,它发现了错误Gemfile - 它是从我的项目(.)使用的Gemfile,而不是生成目录(target/sample_project)。

如何通过Serverspec/Rspec测试调用rakebundler命令?

示例代码:

require "spec_helper" 
require 'serverspec' 
require 'fileutils' 

set :backend, :exec 
set :login_shell, true 

describe "Generated Template" do 
    output_dir='target' 
    project_dir="#{output_dir}/sample_project" 

    # Hooks omitted to create the sample_project 
    # and change working directory to `project_dir` 

    describe command('rake -T') do 
    its(:stdout) { should include "rake serverspec:localhost" } 
    its(:stdout) { should include "rake serverspec:my_app" } 
    end 
end 
+0

你可以在命令中加入'cd target/sample_project && rake && cd -'吗? – Kris

+0

我试过了。我实际上已经添加了一个周围的钩子来改变当前目录:'around(:example)do Dir.chdir(project_dir)end'。这按预期工作 - 我有另一个例子来检查工作目录是否符合预期。 – Tim

+0

挂钩可能无法工作,因为将启动一个新的子进程,该子进程可能没有与父进程相同的当前工作目录。你有没有尝试在命令中放入'cd',以便它在子进程的上下文中执行? – Kris

回答

0

捆扎机具有提供运行记录在这里的外部shell命令:http://bundler.io/v1.3/man/bundle-exec.1.html

运行捆绑/ rake任务可能使用RSpec的使用Bundler.with_clean_env,而不是Serverspec。

require 'bundler' 
require 'rspec' 
RSpec.describe "Generated Template" do 

    output_dir='target' 
    project_dir="#{output_dir}/sample_project" 

    around(:example) do |example| 
    #Change context, so we are in the generated project directory 
    orig_dir=Dir.pwd 

    Dir.chdir(project_dir) 
    example.run 
    Dir.chdir(orig_dir) 

    end 

    around(:example) do |example| 
    Bundler.with_clean_env do 
     example.run 
    end 
    end 

    it "should include localhost" do 
    expect(`rake -T 2>&1`).to include "rake serverspec:localhost" 
    end 
end