-1

I have a project to create a template ruby project.

I am using serverspec and want to verify the behaviour of the template.

However, using command(`rake -T`) fails. If I execute the command manually, it works as expected.

Debugging, when the test is running in Serverspec, it finds the wrong Gemfile - it is using the Gemfile from my project (.), not the generated directory (target/sample_project).

How can I invoke rake or bundler commands withing a Serverspec/Rspec test?

sample code:

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
Tim
  • 726
  • 5
  • 18
  • could you add `cd target/sample_project && rake && cd -` to the command? – Kris Mar 07 '17 at 11:31
  • I've tried that. I have actually added an around hook, to change the current directory: `around(:example) do Dir.chdir(project_dir) end`. This works as expected - I have another example to check that the working directory is as expected. – Tim Mar 07 '17 at 11:33
  • The hook might not work because a new child process will be started which may not have the same current working directory as the parent process. Did you try to put the `cd` inside the command so it is executed in the context of the child process? – Kris Mar 07 '17 at 13:34
  • Yes. I've also confirmed that the hook is working as expected using `pwd && rake`. I've set `set :shell, '/bin/bash'` which is getting me further, but I'm getting `Warning: PATH set to RVM ruby but GEM_HOME and/or GEM_PATH not set` – Tim Mar 08 '17 at 00:46

1 Answers1

1

Bundler has provision for running external shell commands documented here: http://bundler.io/v1.3/man/bundle-exec.1.html

Running bundler/rake tasks is possible using rspec using Bundler.with_clean_env, instead of 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
Tim
  • 726
  • 5
  • 18