2014-09-03 67 views
1

我使用serverspec來執行服務器的遠程測試。是否可以在serverspec中包含通用測試?

我有一些不同的測試,這是所有工作的優良:

`-- spec 
    |-- builder.example.org.uk 
     \ host_spec.rb 
    |-- chat.example.org.uk 
     \ host_spec.rb 
    |-- docker.example.org.uk 
     \ host_spec.rb 
    \-- git.example.org.uk 
     \ host_spec.rb 

但是每個主機測試有很多重複的,因爲我想確保每個主機有sshd運行,例如。

我試過幾種不同的方式創建spec/common_tests.rb但每次都失敗。在spec/chat.example.org.uk/host_spec.rb

describe command("lsb_release -d") do 
    its(:stdout) { should match /wheezy/ } 
end 

然後:例如添加spec/common.rb

require 'common' 

然而,這似乎一下子要連接到不同的主機,但失敗了:

shelob ~ $ bundle exec rake spec:ssh.example.org.uk 
/usr/bin/ruby1.9.1 -S rspec spec/ssh.example.org.uk/host_spec.rb 
F..................... 

Failures: 

    1) Command "lsb_release -d" stdout 
     On host `ssh.example.org.uk` 
     Failure/Error: Unable to find matching line from backtrace 
     SocketError: getaddrinfo: Name or service not known 

所以我的問題是雙重:

  • 是否可以包含來自外部文件的常見測試?
  • 如果是這樣,我該如何做到這一點?
+0

如何symlinking規格到主機目錄? – 2014-09-03 14:32:22

+0

可悲的是,這是行不通的。 – 2014-09-03 14:44:25

+0

目前我已經使用'cpp'將hack文件包含在規範中,並編寫了'Makefile'來完成必要的工作。不愉快,但它確實有效。 – 2014-09-04 01:32:52

回答

2

我不確定您的示例是否存在拼寫錯誤,因爲它似乎完全符合您的要求。您正在運行bundle exec rake spec:ssh.example.org.uk,它正在運行ssh.example.org.uk

serverspec documentation建議運行共享規格的另一種方式。而不是由主機組織您的文件,你應該組織他們角色。例如:

`-- spec 
    |-- app 
    | `-- ruby_spec.rb 
    |-- base 
    | `-- users_and_groups_spec.rb 
    |-- db 
    | `-- mysql_spec.rb 
    |-- proxy 
    | `-- nginx_spec.rb 
    `-- spec_helper.rb 

然後,在你Rakefile,您的主機映射到角色:

hosts = [{name: 'www.example.org.uk', roles: %w(base app)}, 
     {name: 'db.example.org.uk', roles: %w(base db)}] 

然後,您可以提供通過設置主機地址爲一個環境變量運行命令的ServerSpecTask,由壓倒一切的RSpec's spec_command method

class ServerspecTask < RSpec::Core::RakeTask 
    attr_accessor :target 

    def spec_command 
    cmd = super 
    "env TARGET_HOST=#{target} #{cmd}" 
    end 

end 

namespace :serverspec do 
    hosts.each do |host| 
    desc "Run serverspec to #{host[:name]}" 
    ServerspecTask.new(host[:name].to_sym) do |t| 
     t.target = host[:name] 
     t.pattern = 'spec/{' + host[:roles].join(',') + '}/*_spec.rb' 
    end 
    end 
end 

然後終於,更新您的spec_helper.rb來讀取環境VA riable和使用它作爲主機:

RSpec.configure do |c| 
    c.host = ENV['TARGET_HOST'] 
    options = Net::SSH::Config.for(c.host) 
    user = options[:user] || Etc.getlogin 
    c.ssh = Net::SSH.start(c.host, user, options) 
    c.os = backend.check_os 
end 
+0

它似乎確實如此 - 但總之,如果您在工作主機中包含/需要文件,則會收到關於「名稱或服務未知」的虛假錯誤。 – 2014-09-07 20:22:40

+0

在我目前的情況下,按角色分組對於我來說並不真正起作用,但它似乎是最接近的_supported_解決方案,所以我猜儘管它不滿足,我應該給你賞金。 – 2014-09-07 20:23:09

+0

「名稱或服務未知」表明它試圖通過DNS解析主機名(例如,查找「foo.example」。com「不會返回IP地址),這可能表明你處於不受支持的水域,正如你所建議的那樣,但是值得仔細檢查是否有錯別字 – 2014-09-07 23:29:48

相關問題