1

我是 rspec 的新手,我正在尝试了解如何编写一些特定的测试。

背景:

  • 我正在测试一个 Sinatra 应用程序
  • 该应用程序连接到多个数据库
  • 我已将这些数据库的用户名/密码定义为环境变量,并在代码中引用这些变量。

我有工作测试,所以我知道如何测试环境变量的存在。

我是这样做的:

27     it "should know the username for each SUBDOMAIN in the list" do
28       @dm.domains.each do |dom|
29         ENV['C_USERNAME_' + dom].nil?.should eq(false)
30       end
31     end

正如我所说,测试有效。唯一的问题是,当它失败时,不清楚哪个 dom 没有设置环境变量。失败测试的结果如下所示:

    dhaskew@Air1:~/code/projects/rules$ rake spec
   /Users/dhaskew/.rvm/rubies/ruby-1.9.3-p194/bin/ruby -S rspec ./spec/c_spec.rb   ./spec/main_spec.rb ./spec/routes_spec.rb
   ..F*.....*

    Pending:
      My Site Domain Manager should know the password for each SUBDOMAIN in the list
      # Not yet implemented
      # ./spec/c_spec.rb:33
      My Site GET '/rules/SUBDOMAINS' should test all subdomains
      # Not yet implemented
      # ./spec/routes_spec.rb:28

   Failures:

     1) My Site Domain Manager should know the username for each SUBDOMAIN in the list
        Failure/Error: ENV['C_USERNAME_' + dom].nil?.should eq(false)

          expected: false
          got: true

          (compared using ==)
         # ./spec/c_spec.rb:29:in `block (4 levels) in <top (required)>'
         # ./spec/c_spec.rb:28:in `each'
         # ./spec/c_spec.rb:28:in `block (3 levels) in <top (required)>'

     Finished in 0.05095 seconds
     10 examples, 1 failure, 2 pending

    Failed examples:

    rspec ./spec/c_spec.rb:27 # My Site Domain Manager should know the username for each SUBDOMAIN in the list
    rake aborted!

问题:如何更好地编写此测试,以便我可以看到未定义的环境变量。

谢谢。

4

1 回答 1

0

一个简单的解决方案是:it动态生成测试。一般来说,争取每个场景/it块进行一次测试。在这种情况下:

@dm.domains.each do |dom|
  it "should know the username for #{dom} in the list" do
    ENV['C_USERNAME_' + dom].should_not be_nil
  end
end

更新

这是一个更完整的例子。您需要在块@dm之外声明before它才能使用。

class DomainManager
  attr_reader :domains

  def initialize(domains)
    @domains = domains
  end
end

describe DomainManager do
  @dm = DomainManager.new( %w(example.com example.org))

  @dm.domains.each do |dom|
    it "should know the username for #{dom} in the list" do
      ENV['C_USERNAME_' + dom].should_not be_nil
    end
  end
end
于 2012-09-08T00:30:06.010 回答