diff options
author | Claire McQuin <mcquin@users.noreply.github.com> | 2014-11-07 14:48:12 -0800 |
---|---|---|
committer | Claire McQuin <mcquin@users.noreply.github.com> | 2014-11-07 14:48:12 -0800 |
commit | 1888a8a9c5cbc1bdcfb1d9aa919a911c72cbbff4 (patch) | |
tree | 2e3a93f98865ad7091fdd24319b1aba6d03dcc70 | |
parent | bf6340a113dd0c37e2084c70007d201742f11e9d (diff) | |
parent | 51430f7f2c25773f5ad3c05015eed95d315f798d (diff) | |
download | chef-1888a8a9c5cbc1bdcfb1d9aa919a911c72cbbff4.tar.gz |
Merge pull request #2324 from opscode/mcquin/rspec-3
Update to RSpec 3
321 files changed, 7505 insertions, 7488 deletions
@@ -1,2 +1,2 @@ --color --fs +-fd diff --git a/CHANGELOG.md b/CHANGELOG.md index c98c58d9c5..e937b716d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -236,6 +236,7 @@ * The Windows env provider will delete elements even if they are only in ENV (and not in the registry) * Allow events to be logged to Windows Event Log * Fixed bug in env resource where a value containing the delimiter could never correctly match the existing values +* Update Chef to use RSpec 3. ## 11.16.4 diff --git a/chef.gemspec b/chef.gemspec index e7b6aa35ff..8e906a0ef1 100644 --- a/chef.gemspec +++ b/chef.gemspec @@ -41,9 +41,9 @@ Gem::Specification.new do |s| s.add_development_dependency "rake", "~> 10.1.0" # rspec_junit_formatter 0.2.0 drops ruby 1.8.7 support - s.add_development_dependency "rspec_junit_formatter", "~> 0.1.0" + s.add_development_dependency "rspec_junit_formatter", "~> 0.2.0" - %w(rspec-core rspec-expectations rspec-mocks).each { |gem| s.add_development_dependency gem, "~> 2.14.0" } + %w(rspec-core rspec-expectations rspec-mocks).each { |gem| s.add_development_dependency gem, "~> 3.0" } s.bindir = "bin" s.executables = %w( chef-client chef-solo knife chef-shell shef chef-apply ) diff --git a/pedant.gemfile b/pedant.gemfile index d4ac849707..baa3e9aece 100644 --- a/pedant.gemfile +++ b/pedant.gemfile @@ -2,7 +2,6 @@ source "https://rubygems.org" gemspec :name => "chef" gem 'rest-client', :github => 'opscode/rest-client', :branch => 'lcg/1.6.7-version-lying' -gem 'chef-pedant', :github => 'opscode/chef-pedant', :branch => "metadata-name-fix" # TODO figure out how to grab this stuff from the main Gemfile gem "activesupport", "< 4.0.0", :group => :compat_testing, :platform => "ruby" diff --git a/spec/functional/application_spec.rb b/spec/functional/application_spec.rb index 4a0fdff8f8..00ff0f702a 100644 --- a/spec/functional/application_spec.rb +++ b/spec/functional/application_spec.rb @@ -52,7 +52,7 @@ describe Chef::Application do shell_out("echo $http_proxy") end - so.stdout.chomp.should == "http://proxy.example.org:8080" + expect(so.stdout.chomp).to eq("http://proxy.example.org:8080") end end end diff --git a/spec/functional/dsl/reboot_pending_spec.rb b/spec/functional/dsl/reboot_pending_spec.rb index 125c952a55..14dd9412d5 100644 --- a/spec/functional/dsl/reboot_pending_spec.rb +++ b/spec/functional/dsl/reboot_pending_spec.rb @@ -48,18 +48,18 @@ describe Chef::DSL::RebootPending, :windows_only do describe "when there is nothing to indicate a reboot is pending" do it "should return false" do - pending "Found existing registry keys" if registry_unsafe? - expect(recipe.reboot_pending?).to be_false + skip "Found existing registry keys" if registry_unsafe? + expect(recipe.reboot_pending?).to be_falsey end end describe 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations' do it "returns true if the registry value exists" do - pending "Found existing registry keys" if registry_unsafe? + skip "Found existing registry keys" if registry_unsafe? registry.set_value('HKLM\SYSTEM\CurrentControlSet\Control\Session Manager', { :name => 'PendingFileRenameOperations', :type => :multi_string, :data => ['\??\C:\foo.txt|\??\C:\bar.txt'] }) - expect(recipe.reboot_pending?).to be_true + expect(recipe.reboot_pending?).to be_truthy end after do @@ -71,10 +71,10 @@ describe Chef::DSL::RebootPending, :windows_only do describe 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' do it "returns true if the registry key exists" do - pending "Found existing registry keys" if registry_unsafe? + skip "Found existing registry keys" if registry_unsafe? registry.create_key('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired', false) - expect(recipe.reboot_pending?).to be_true + expect(recipe.reboot_pending?).to be_truthy end after do @@ -87,10 +87,10 @@ describe Chef::DSL::RebootPending, :windows_only do describe 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootRequired' do it "returns true if the registry key exists" do pending "Permissions are limited to 'TrustedInstaller' by default" - pending "Found existing registry keys" if registry_unsafe? + skip "Found existing registry keys" if registry_unsafe? registry.create_key('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootRequired', false) - expect(recipe.reboot_pending?).to be_true + expect(recipe.reboot_pending?).to be_truthy end after do @@ -102,12 +102,12 @@ describe Chef::DSL::RebootPending, :windows_only do describe 'HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile\Flags' do it "returns true if the registry key exists" do - pending "Found existing registry keys" if registry_unsafe? + skip "Found existing registry keys" if registry_unsafe? registry.create_key('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile', true) registry.set_value('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile', { :name => 'Flags', :type => :dword, :data => 3 }) - expect(recipe.reboot_pending?).to be_true + expect(recipe.reboot_pending?).to be_truthy end after do diff --git a/spec/functional/dsl/registry_helper_spec.rb b/spec/functional/dsl/registry_helper_spec.rb index 452c4c2799..df5b09f1f6 100644 --- a/spec/functional/dsl/registry_helper_spec.rb +++ b/spec/functional/dsl/registry_helper_spec.rb @@ -40,24 +40,24 @@ describe Chef::Resource::RegistryKey, :windows_only do context "tests registry dsl" do it "returns true if registry_key_exists" do - @resource.registry_key_exists?("HKCU\\Software\\Root").should == true + expect(@resource.registry_key_exists?("HKCU\\Software\\Root")).to eq(true) end it "returns true if registry has specified value" do values = @resource.registry_get_values("HKCU\\Software\\Root") - values.include?({:name=>"RootType1",:type=>:string,:data=>"fibrous"}).should == true + expect(values.include?({:name=>"RootType1",:type=>:string,:data=>"fibrous"})).to eq(true) end it "returns true if specified registry_has_subkey" do - @resource.registry_has_subkeys?("HKCU\\Software\\Root").should == true + expect(@resource.registry_has_subkeys?("HKCU\\Software\\Root")).to eq(true) end it "returns true if specified key has specified subkey" do subkeys = @resource.registry_get_subkeys("HKCU\\Software\\Root") - subkeys.include?("Branch").should == true + expect(subkeys.include?("Branch")).to eq(true) end it "returns true if registry_value_exists" do - @resource.registry_value_exists?("HKCU\\Software\\Root", {:name=>"RootType1", :type=>:string, :data=>"fibrous"}).should == true + expect(@resource.registry_value_exists?("HKCU\\Software\\Root", {:name=>"RootType1", :type=>:string, :data=>"fibrous"})).to eq(true) end it "returns true if data_value_exists" do - @resource.registry_data_exists?("HKCU\\Software\\Root", {:name=>"RootType1", :type=>:string, :data=>"fibrous"}).should == true + expect(@resource.registry_data_exists?("HKCU\\Software\\Root", {:name=>"RootType1", :type=>:string, :data=>"fibrous"})).to eq(true) end end end diff --git a/spec/functional/event_loggers/windows_eventlog_spec.rb b/spec/functional/event_loggers/windows_eventlog_spec.rb index c50bc7e00f..4e383dd429 100644 --- a/spec/functional/event_loggers/windows_eventlog_spec.rb +++ b/spec/functional/event_loggers/windows_eventlog_spec.rb @@ -37,21 +37,21 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only, :not_supported_o let(:mock_exception) { double('Exception', {message: SecureRandom.uuid, backtrace:[SecureRandom.uuid, SecureRandom.uuid]})} it 'is available' do - Chef::EventLoggers::WindowsEventLogger.available?.should be_true + expect(Chef::EventLoggers::WindowsEventLogger.available?).to be_truthy end it 'writes run_start event with event_id 10000 and contains version' do logger.run_start(version) expect(event_log.read(flags, offset).any? { |e| e.source == 'Chef' && e.event_id == 10000 && - e.string_inserts[0].include?(version)}).to be_true + e.string_inserts[0].include?(version)}).to be_truthy end it 'writes run_started event with event_id 10001 and contains the run_id' do logger.run_started(run_status) expect(event_log.read(flags, offset).any? { |e| e.source == 'Chef' && e.event_id == 10001 && - e.string_inserts[0].include?(run_id)}).to be_true + e.string_inserts[0].include?(run_id)}).to be_truthy end it 'writes run_completed event with event_id 10002 and contains the run_id and elapsed time' do @@ -61,7 +61,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only, :not_supported_o expect(event_log.read(flags, offset).any? { |e| e.source == 'Chef' && e.event_id == 10002 && e.string_inserts[0].include?(run_id) && e.string_inserts[1].include?(elapsed_time.to_s) - }).to be_true + }).to be_truthy end it 'writes run_failed event with event_id 10003 and contains the run_id, elapsed time, and exception info' do @@ -76,7 +76,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only, :not_supported_o e.string_inserts[3].include?(mock_exception.message) && e.string_inserts[4].include?(mock_exception.backtrace[0]) && e.string_inserts[4].include?(mock_exception.backtrace[1]) - end).to be_true + end).to be_truthy end end diff --git a/spec/functional/file_content_management/deploy_strategies_spec.rb b/spec/functional/file_content_management/deploy_strategies_spec.rb index dd1ef6228f..bcd171eb73 100644 --- a/spec/functional/file_content_management/deploy_strategies_spec.rb +++ b/spec/functional/file_content_management/deploy_strategies_spec.rb @@ -56,11 +56,11 @@ shared_examples_for "a content deploy strategy" do it "touches the file to create it (UNIX)", :unix_only do content_deployer.create(target_file_path) - File.should exist(target_file_path) + expect(File).to exist(target_file_path) file_info = File.stat(target_file_path) - file_info.should be_owned - file_info.should be_file - normalize_mode(file_info.mode).should == default_mode + expect(file_info).to be_owned + expect(file_info).to be_file + expect(normalize_mode(file_info.mode)).to eq(default_mode) end ## @@ -89,10 +89,10 @@ shared_examples_for "a content deploy strategy" do it "touches the file to create it (Windows)", :windows_only do content_deployer.create(target_file_path) - File.should exist(target_file_path) + expect(File).to exist(target_file_path) file_info = File.stat(target_file_path) - file_info.should be_owned - file_info.should be_file + expect(file_info).to be_owned + expect(file_info).to be_file parent_aces = parent_inheritable_aces security_obj = Chef::ReservedNames::Win32::Security::SecurableObject.new(target_file_path) @@ -106,7 +106,7 @@ shared_examples_for "a content deploy strategy" do end self_aces.each_with_index do |ace, index| - ace.mask.should == parent_aces[index].mask + expect(ace.mask).to eq(parent_aces[index].mask) end end end @@ -147,7 +147,7 @@ shared_examples_for "a content deploy strategy" do content_deployer.deploy(staging_file_path, target_file_path) updated_info = File.stat(target_file_path) - unix_invariant_properies(original_info).should == unix_invariant_properies(updated_info) + expect(unix_invariant_properies(original_info)).to eq(unix_invariant_properies(updated_info)) end it "maintains invariant properties on Windows", :windows_only do @@ -155,12 +155,12 @@ shared_examples_for "a content deploy strategy" do content_deployer.deploy(staging_file_path, target_file_path) updated_info = Chef::ReservedNames::Win32::Security::SecurableObject.new(target_file_path) - win_invariant_properties(original_info).should == win_invariant_properties(updated_info) + expect(win_invariant_properties(original_info)).to eq(win_invariant_properties(updated_info)) end it "updates the target with content from staged" do content_deployer.deploy(staging_file_path, target_file_path) - binread(target_file_path).should == staging_file_content + expect(binread(target_file_path)).to eq(staging_file_content) end context "when the owner of the target file is not the owner of the staging file", :requires_root do @@ -174,7 +174,7 @@ shared_examples_for "a content deploy strategy" do content_deployer.deploy(staging_file_path, target_file_path) updated_info = File.stat(target_file_path) - unix_invariant_properies(original_info).should == unix_invariant_properies(updated_info) + expect(unix_invariant_properies(original_info)).to eq(unix_invariant_properies(updated_info)) end end diff --git a/spec/functional/http/simple_spec.rb b/spec/functional/http/simple_spec.rb index fec71351df..36468b4eba 100644 --- a/spec/functional/http/simple_spec.rb +++ b/spec/functional/http/simple_spec.rb @@ -85,7 +85,7 @@ describe Chef::HTTP::Simple do before do Chef::Log.level = :debug @debug_log = '' - Chef::Log.stub(:debug) { |str| @debug_log << str } + allow(Chef::Log).to receive(:debug) { |str| @debug_log << str } end let(:source) { 'http://localhost:9000' } diff --git a/spec/functional/knife/cookbook_delete_spec.rb b/spec/functional/knife/cookbook_delete_spec.rb index 4773fd2185..15ac8f55ab 100644 --- a/spec/functional/knife/cookbook_delete_spec.rb +++ b/spec/functional/knife/cookbook_delete_spec.rb @@ -51,9 +51,9 @@ describe Chef::Knife::CookbookDelete do end it "logs an error and exits" do - @knife.ui.stub(:stderr).and_return(@log_output) - lambda {@knife.run}.should raise_error(SystemExit) - @log_output.string.should match(/Cannot find a cookbook named no-such-cookbook to delete/) + allow(@knife.ui).to receive(:stderr).and_return(@log_output) + expect {@knife.run}.to raise_error(SystemExit) + expect(@log_output.string).to match(/Cannot find a cookbook named no-such-cookbook to delete/) end end @@ -67,33 +67,33 @@ describe Chef::Knife::CookbookDelete do it "asks for confirmation, then deletes the cookbook" do stdin, stdout = StringIO.new("y\n"), StringIO.new - @knife.ui.stub(:stdin).and_return(stdin) - @knife.ui.stub(:stdout).and_return(stdout) + allow(@knife.ui).to receive(:stdin).and_return(stdin) + allow(@knife.ui).to receive(:stdout).and_return(stdout) cb100_deleted = false @api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) { cb100_deleted = true; "[\"true\"]" } @knife.run - stdout.string.should match(/#{Regexp.escape('Do you really want to delete obsolete-cookbook version 1.0.0? (Y/N)')}/) - cb100_deleted.should be_true + expect(stdout.string).to match(/#{Regexp.escape('Do you really want to delete obsolete-cookbook version 1.0.0? (Y/N)')}/) + expect(cb100_deleted).to be_truthy end it "asks for confirmation before purging" do @knife.config[:purge] = true stdin, stdout = StringIO.new("y\ny\n"), StringIO.new - @knife.ui.stub(:stdin).and_return(stdin) - @knife.ui.stub(:stdout).and_return(stdout) + allow(@knife.ui).to receive(:stdin).and_return(stdin) + allow(@knife.ui).to receive(:stdout).and_return(stdout) cb100_deleted = false @api.delete("/cookbooks/obsolete-cookbook/1.0.0?purge=true", 200) { cb100_deleted = true; "[\"true\"]" } @knife.run - stdout.string.should match(/#{Regexp.escape('Are you sure you want to purge files')}/) - stdout.string.should match(/#{Regexp.escape('Do you really want to delete obsolete-cookbook version 1.0.0? (Y/N)')}/) - cb100_deleted.should be_true + expect(stdout.string).to match(/#{Regexp.escape('Are you sure you want to purge files')}/) + expect(stdout.string).to match(/#{Regexp.escape('Do you really want to delete obsolete-cookbook version 1.0.0? (Y/N)')}/) + expect(cb100_deleted).to be_truthy end @@ -117,22 +117,22 @@ describe Chef::Knife::CookbookDelete do @api.delete("/cookbooks/obsolete-cookbook/1.2.0", 200) { cb120_deleted = true; "[\"true\"]" } @knife.run - cb100_deleted.should be_true - cb110_deleted.should be_true - cb120_deleted.should be_true + expect(cb100_deleted).to be_truthy + expect(cb110_deleted).to be_truthy + expect(cb120_deleted).to be_truthy end it "asks which version to delete and deletes that when not given the -a flag" do cb100_deleted = cb110_deleted = cb120_deleted = nil @api.delete("/cookbooks/obsolete-cookbook/1.0.0", 200) { cb100_deleted = true; "[\"true\"]" } stdin, stdout = StringIO.new, StringIO.new - @knife.ui.stub(:stdin).and_return(stdin) - @knife.ui.stub(:stdout).and_return(stdout) + allow(@knife.ui).to receive(:stdin).and_return(stdin) + allow(@knife.ui).to receive(:stdout).and_return(stdout) stdin << "1\n" stdin.rewind @knife.run - cb100_deleted.should be_true - stdout.string.should match(/Which version\(s\) do you want to delete\?/) + expect(cb100_deleted).to be_truthy + expect(stdout.string).to match(/Which version\(s\) do you want to delete\?/) end it "deletes all versions of the cookbook when not given the -a flag and the user chooses to delete all" do @@ -142,14 +142,14 @@ describe Chef::Knife::CookbookDelete do @api.delete("/cookbooks/obsolete-cookbook/1.2.0", 200) { cb120_deleted = true; "[\"true\"]" } stdin, stdout = StringIO.new("4\n"), StringIO.new - @knife.ui.stub(:stdin).and_return(stdin) - @knife.ui.stub(:stdout).and_return(stdout) + allow(@knife.ui).to receive(:stdin).and_return(stdin) + allow(@knife.ui).to receive(:stdout).and_return(stdout) @knife.run - cb100_deleted.should be_true - cb110_deleted.should be_true - cb120_deleted.should be_true + expect(cb100_deleted).to be_truthy + expect(cb110_deleted).to be_truthy + expect(cb120_deleted).to be_truthy end end diff --git a/spec/functional/knife/exec_spec.rb b/spec/functional/knife/exec_spec.rb index 7eb52d01df..0a9177b5e8 100644 --- a/spec/functional/knife/exec_spec.rb +++ b/spec/functional/knife/exec_spec.rb @@ -41,7 +41,7 @@ describe Chef::Knife::Exec do @server.stop end - pending "executes a script in the context of the chef-shell main context", :ruby_18_only + skip "executes a script in the context of the chef-shell main context", :ruby_18_only it "executes a script in the context of the chef-shell main context", :ruby_gte_19_only do @node = Chef::Node.new @@ -51,7 +51,7 @@ describe Chef::Knife::Exec do code = "$output.puts nodes.all" @knife.config[:exec] = code @knife.run - $output.string.should match(%r{node\[ohai-world\]}) + expect($output.string).to match(%r{node\[ohai-world\]}) end end diff --git a/spec/functional/knife/smoke_test.rb b/spec/functional/knife/smoke_test.rb index 6ccd462516..607e8065cf 100644 --- a/spec/functional/knife/smoke_test.rb +++ b/spec/functional/knife/smoke_test.rb @@ -29,6 +29,6 @@ describe "knife smoke tests" do knife_cmd = Mixlib::ShellOut.new("#{knife_path} -v") knife_cmd.run_command knife_cmd.error! - knife_cmd.stdout.should include(Chef::VERSION) + expect(knife_cmd.stdout).to include(Chef::VERSION) end end diff --git a/spec/functional/knife/ssh_spec.rb b/spec/functional/knife/ssh_spec.rb index 40d71859c7..cde702e8b2 100644 --- a/spec/functional/knife/ssh_spec.rb +++ b/spec/functional/knife/ssh_spec.rb @@ -40,7 +40,7 @@ describe Chef::Knife::Ssh do it "uses the ssh_identity_file" do @knife.run - @knife.config[:identity_file].should == "~/.ssh/aws.rsa" + expect(@knife.config[:identity_file]).to eq("~/.ssh/aws.rsa") end end @@ -52,7 +52,7 @@ describe Chef::Knife::Ssh do it "uses the ssh_identity_file" do @knife.run - @knife.config[:identity_file].should == "~/.ssh/aws.rsa" + expect(@knife.config[:identity_file]).to eq("~/.ssh/aws.rsa") end end @@ -64,13 +64,13 @@ describe Chef::Knife::Ssh do it "should use the value on the command line" do @knife.run - @knife.config[:identity_file].should == "~/.ssh/aws.rsa" + expect(@knife.config[:identity_file]).to eq("~/.ssh/aws.rsa") end it "should override what is set in knife.rb" do Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/other.rsa" @knife.run - @knife.config[:identity_file].should == "~/.ssh/aws.rsa" + expect(@knife.config[:identity_file]).to eq("~/.ssh/aws.rsa") end end @@ -82,7 +82,7 @@ describe Chef::Knife::Ssh do it "uses the default" do @knife.run - @knife.config[:identity_file].should == nil + expect(@knife.config[:identity_file]).to eq(nil) end end end @@ -95,7 +95,7 @@ describe Chef::Knife::Ssh do it "uses the ssh_port" do @knife.run - @knife.config[:ssh_port].should == "31337" + expect(@knife.config[:ssh_port]).to eq("31337") end end end @@ -109,7 +109,7 @@ describe Chef::Knife::Ssh do it "uses the ssh_user" do @knife.run - @knife.config[:ssh_user].should == "ubuntu" + expect(@knife.config[:ssh_user]).to eq("ubuntu") end end @@ -121,7 +121,7 @@ describe Chef::Knife::Ssh do it "uses the ssh_user" do @knife.run - @knife.config[:ssh_user].should == "ubuntu" + expect(@knife.config[:ssh_user]).to eq("ubuntu") end end @@ -133,13 +133,13 @@ describe Chef::Knife::Ssh do it "should use the value on the command line" do @knife.run - @knife.config[:ssh_user].should == "ubuntu" + expect(@knife.config[:ssh_user]).to eq("ubuntu") end it "should override what is set in knife.rb" do Chef::Config[:knife][:ssh_user] = "root" @knife.run - @knife.config[:ssh_user].should == "ubuntu" + expect(@knife.config[:ssh_user]).to eq("ubuntu") end end @@ -151,7 +151,7 @@ describe Chef::Knife::Ssh do it "uses the default (current user)" do @knife.run - @knife.config[:ssh_user].should == nil + expect(@knife.config[:ssh_user]).to eq(nil) end end end @@ -165,7 +165,7 @@ describe Chef::Knife::Ssh do it "uses the ssh_attribute" do @knife.run - @knife.config[:attribute].should == "ec2.public_hostname" + expect(@knife.config[:attribute]).to eq("ec2.public_hostname") end end @@ -177,7 +177,7 @@ describe Chef::Knife::Ssh do it "uses the default" do @knife.run - @knife.config[:attribute].should == "fqdn" + expect(@knife.config[:attribute]).to eq("fqdn") end end @@ -189,7 +189,7 @@ describe Chef::Knife::Ssh do it "should use the value on the command line" do @knife.run - @knife.config[:attribute].should == "ec2.public_hostname" + expect(@knife.config[:attribute]).to eq("ec2.public_hostname") end it "should override what is set in knife.rb" do @@ -198,7 +198,7 @@ describe Chef::Knife::Ssh do # Then we run knife with the -a flag, which sets the above variable setup_knife(['-a ec2.public_hostname', '*:*', 'uptime']) @knife.run - @knife.config[:attribute].should == "ec2.public_hostname" + expect(@knife.config[:attribute]).to eq("ec2.public_hostname") end end end @@ -211,9 +211,9 @@ describe Chef::Knife::Ssh do end it "uses the ssh_gateway" do - @knife.session.should_receive(:via).with("ec2.public_hostname", "user", {}) + expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", {}) @knife.run - @knife.config[:ssh_gateway].should == "user@ec2.public_hostname" + expect(@knife.config[:ssh_gateway]).to eq("user@ec2.public_hostname") end end @@ -224,9 +224,9 @@ describe Chef::Knife::Ssh do end it "uses the ssh_gateway" do - @knife.session.should_receive(:via).with("ec2.public_hostname", "user", {}) + expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", {}) @knife.run - @knife.config[:ssh_gateway].should == "user@ec2.public_hostname" + expect(@knife.config[:ssh_gateway]).to eq("user@ec2.public_hostname") end end @@ -234,13 +234,13 @@ describe Chef::Knife::Ssh do before do setup_knife(['-G user@ec2.public_hostname', '*:*', 'uptime']) Chef::Config[:knife][:ssh_gateway] = nil - @knife.session.stub(:via) do |host, user, options| + allow(@knife.session).to receive(:via) do |host, user, options| raise Net::SSH::AuthenticationFailed unless options[:password] end end it "should prompt the user for a password" do - @knife.ui.should_receive(:ask).with("Enter the password for user@ec2.public_hostname: ").and_return("password") + expect(@knife.ui).to receive(:ask).with("Enter the password for user@ec2.public_hostname: ").and_return("password") @knife.run end end @@ -252,7 +252,7 @@ describe Chef::Knife::Ssh do # if available, but #merge_configs (which is called by #configure_chef) is # necessary to have default options merged in. @knife.merge_configs - @knife.stub(:ssh_command).and_return { 0 } + allow(@knife).to receive(:ssh_command) { 0 } @api = TinyServer::API.instance @api.clear diff --git a/spec/functional/provider/remote_file/cache_control_data_spec.rb b/spec/functional/provider/remote_file/cache_control_data_spec.rb index 63a4578c69..41f228ae3c 100755 --- a/spec/functional/provider/remote_file/cache_control_data_spec.rb +++ b/spec/functional/provider/remote_file/cache_control_data_spec.rb @@ -64,9 +64,9 @@ describe Chef::Provider::RemoteFile::CacheControlData do it "writes the data to the cache and the same data can be read back" do cache_control_data.save saved_cache_control_data = Chef::Provider::RemoteFile::CacheControlData.load_and_validate(uri, file_checksum) - saved_cache_control_data.etag.should == cache_control_data.etag - saved_cache_control_data.mtime.should == cache_control_data.mtime - saved_cache_control_data.checksum.should == cache_control_data.checksum + expect(saved_cache_control_data.etag).to eq(cache_control_data.etag) + expect(saved_cache_control_data.mtime).to eq(cache_control_data.mtime) + expect(saved_cache_control_data.checksum).to eq(cache_control_data.checksum) end # Cover the very long remote file path case -- see CHEF-4422 where @@ -81,17 +81,17 @@ describe Chef::Provider::RemoteFile::CacheControlData do let(:uri) { uri_exceeds_file_system_limit } it "writes data to the cache" do - lambda do + expect do cache_control_data.save - end.should_not raise_error + end.not_to raise_error end it "writes the data to the cache and the same data can be read back" do cache_control_data.save saved_cache_control_data = Chef::Provider::RemoteFile::CacheControlData.load_and_validate(uri, file_checksum) - saved_cache_control_data.etag.should == cache_control_data.etag - saved_cache_control_data.mtime.should == cache_control_data.mtime - saved_cache_control_data.checksum.should == cache_control_data.checksum + expect(saved_cache_control_data.etag).to eq(cache_control_data.etag) + expect(saved_cache_control_data.mtime).to eq(cache_control_data.mtime) + expect(saved_cache_control_data.checksum).to eq(cache_control_data.checksum) end end diff --git a/spec/functional/provider/whyrun_safe_ruby_block_spec.rb b/spec/functional/provider/whyrun_safe_ruby_block_spec.rb index 150d46d384..b3c2333e9a 100644 --- a/spec/functional/provider/whyrun_safe_ruby_block_spec.rb +++ b/spec/functional/provider/whyrun_safe_ruby_block_spec.rb @@ -44,8 +44,8 @@ describe Chef::Resource::WhyrunSafeRubyBlock do it "updates the evil laugh, even in why-run mode" do new_resource.run_action(new_resource.action) - $evil_global_evil_laugh.should == :mwahahaha - new_resource.should be_updated + expect($evil_global_evil_laugh).to eq(:mwahahaha) + expect(new_resource).to be_updated end end end diff --git a/spec/functional/rebooter_spec.rb b/spec/functional/rebooter_spec.rb index 8006580d5c..763021607b 100644 --- a/spec/functional/rebooter_spec.rb +++ b/spec/functional/rebooter_spec.rb @@ -70,7 +70,7 @@ describe Chef::Platform::Rebooter do shared_context 'test a reboot method' do def test_rebooter_method(method_sym, is_windows, expected_reboot_str) - Chef::Platform.stub(:windows?).and_return(is_windows) + allow(Chef::Platform).to receive(:windows?).and_return(is_windows) expect(rebooter).to receive(:shell_out!).once.with(expected_reboot_str) expect(rebooter).to receive(method_sym).once.and_call_original rebooter.send(method_sym, run_context.node) diff --git a/spec/functional/resource/aixinit_service_spec.rb b/spec/functional/resource/aixinit_service_spec.rb index a99309187c..3d3234f0f7 100755 --- a/spec/functional/resource/aixinit_service_spec.rb +++ b/spec/functional/resource/aixinit_service_spec.rb @@ -29,11 +29,11 @@ describe Chef::Resource::Service, :requires_root, :aix_only do # Platform specific validation routines. def service_should_be_started(file_name) # The existance of this file indicates that the service was started. - expect(File.exists?("/tmp/#{file_name}")).to be_true + expect(File.exists?("/tmp/#{file_name}")).to be_truthy end def service_should_be_stopped(file_name) - expect(File.exists?("/tmp/#{file_name}")).to be_false + expect(File.exists?("/tmp/#{file_name}")).to be_falsey end def valide_symlinks(expected_output, run_level = nil, status = nil, priority = nil) diff --git a/spec/functional/resource/deploy_revision_spec.rb b/spec/functional/resource/deploy_revision_spec.rb index eae422ac1d..7bc3da9a05 100644 --- a/spec/functional/resource/deploy_revision_spec.rb +++ b/spec/functional/resource/deploy_revision_spec.rb @@ -173,12 +173,12 @@ describe Chef::Resource::DeployRevision, :unix_only => true do it "deploys the app to the target revision (#{target_rev_spec})" do target_rev = send(target_rev_spec) - File.should exist(rel_path("current")) + expect(File).to exist(rel_path("current")) - actual_current_rev.should == target_rev + expect(actual_current_rev).to eq(target_rev) # Is the app code actually there? - File.should exist(rel_path("current/app/app.rb")) + expect(File).to exist(rel_path("current/app/app.rb")) end end @@ -193,12 +193,12 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:latest_rev) it "restarts the application" do - File.should exist(rel_path("current/restart.txt")) - actual_operations_order.should == %w[deploy_to_latest_rev] + expect(File).to exist(rel_path("current/restart.txt")) + expect(actual_operations_order).to eq(%w[deploy_to_latest_rev]) end it "is marked as updated" do - deploy_to_latest_rev.should be_updated_by_last_action + expect(deploy_to_latest_rev).to be_updated_by_last_action end end @@ -215,15 +215,15 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:latest_rev) it "restarts the application after rolling back" do - actual_operations_order.should == %w[deploy_to_latest_rev deploy_to_previous_rev deploy_to_latest_rev_again] + expect(actual_operations_order).to eq(%w[deploy_to_latest_rev deploy_to_previous_rev deploy_to_latest_rev_again]) end it "is marked updated" do - deploy_to_latest_rev_again.should be_updated_by_last_action + expect(deploy_to_latest_rev_again).to be_updated_by_last_action end it "deploys the right code" do - IO.read(rel_path("current/app/app.rb")).should include("this is the fourth version of the app") + expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the fourth version of the app") end end @@ -233,27 +233,27 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end it "creates the required directory tree" do - File.should be_directory(rel_path("releases")) - File.should be_directory(rel_path("shared")) - File.should be_directory(rel_path("releases/#{latest_rev}")) + expect(File).to be_directory(rel_path("releases")) + expect(File).to be_directory(rel_path("shared")) + expect(File).to be_directory(rel_path("releases/#{latest_rev}")) - File.should be_directory(rel_path("current/tmp")) - File.should be_directory(rel_path("current/config")) - File.should be_directory(rel_path("current/public")) + expect(File).to be_directory(rel_path("current/tmp")) + expect(File).to be_directory(rel_path("current/config")) + expect(File).to be_directory(rel_path("current/public")) - File.should be_symlink(rel_path("current")) - File.readlink(rel_path("current")).should == rel_path("releases/#{latest_rev}") + expect(File).to be_symlink(rel_path("current")) + expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}")) end the_app_is_deployed_at_revision(:latest_rev) it "restarts the application" do - File.should exist(rel_path("current/restart.txt")) - actual_operations_order.should == %w[deploy_to_latest_rev] + expect(File).to exist(rel_path("current/restart.txt")) + expect(actual_operations_order).to eq(%w[deploy_to_latest_rev]) end it "is marked as updated" do - deploy_to_latest_rev.should be_updated_by_last_action + expect(deploy_to_latest_rev).to be_updated_by_last_action end end @@ -266,11 +266,11 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:latest_rev) it "does not restart the app" do - actual_operations_order.should == %w[deploy_to_latest_rev] + expect(actual_operations_order).to eq(%w[deploy_to_latest_rev]) end it "is not marked updated" do - deploy_to_latest_rev.should_not be_updated_by_last_action + expect(deploy_to_latest_rev).not_to be_updated_by_last_action end end @@ -284,11 +284,11 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:latest_rev) it "restarts the app" do - actual_operations_order.should == %w[deploy_to_latest_rev deploy_to_latest_rev_again] + expect(actual_operations_order).to eq(%w[deploy_to_latest_rev deploy_to_latest_rev_again]) end it "is marked updated" do - deploy_to_latest_rev.should be_updated_by_last_action + expect(deploy_to_latest_rev).to be_updated_by_last_action end end @@ -302,15 +302,15 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:latest_rev) it "restarts the application after the new deploy" do - actual_operations_order.should == %w[deploy_to_previous_rev deploy_to_latest_rev] + expect(actual_operations_order).to eq(%w[deploy_to_previous_rev deploy_to_latest_rev]) end it "is marked updated" do - deploy_to_previous_rev.should be_updated_by_last_action + expect(deploy_to_previous_rev).to be_updated_by_last_action end it "leaves the old copy of the app around for rollback" do - File.should exist(File.join(deploy_directory, "releases", previous_rev)) + expect(File).to exist(File.join(deploy_directory, "releases", previous_rev)) end end @@ -325,15 +325,15 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:latest_rev) it "restarts the application after rolling back" do - actual_operations_order.should == %w[deploy_to_latest_rev deploy_to_previous_rev deploy_to_latest_rev_again] + expect(actual_operations_order).to eq(%w[deploy_to_latest_rev deploy_to_previous_rev deploy_to_latest_rev_again]) end it "is marked updated" do - deploy_to_latest_rev_again.should be_updated_by_last_action + expect(deploy_to_latest_rev_again).to be_updated_by_last_action end it "deploys the right code" do - IO.read(rel_path("current/app/app.rb")).should include("this is the fourth version of the app") + expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the fourth version of the app") end end @@ -350,31 +350,31 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:previous_rev) it "restarts the application after rolling back" do - actual_operations_order.should == %w[deploy_to_previous_rev deploy_to_latest_rev deploy_to_latest_rev_again] + expect(actual_operations_order).to eq(%w[deploy_to_previous_rev deploy_to_latest_rev deploy_to_latest_rev_again]) end it "is marked updated" do - deploy_to_latest_rev_again.should be_updated_by_last_action + expect(deploy_to_latest_rev_again).to be_updated_by_last_action end it "deploys the right code" do - IO.read(rel_path("current/app/app.rb")).should include("this is the third version of the app") + expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the third version of the app") end it "all_releases after first deploy should have one entry" do - @previous_rev_all_releases.length.should == 1 + expect(@previous_rev_all_releases.length).to eq(1) end it "all_releases after second deploy should have two entries" do - @latest_rev_all_releases.length.should == 2 + expect(@latest_rev_all_releases.length).to eq(2) end it "all_releases after rollback should have one entry" do - @previous_rev_again_all_releases.length.should == 1 + expect(@previous_rev_again_all_releases.length).to eq(1) end it "all_releases after rollback should be the same as after the first deploy" do - @previous_rev_again_all_releases.should == @previous_rev_all_releases + expect(@previous_rev_again_all_releases).to eq(@previous_rev_all_releases) end end @@ -393,31 +393,31 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:previous_rev) it "restarts the application after rolling back" do - actual_operations_order.should == %w[deploy_to_previous_rev deploy_to_latest_rev deploy_to_previous_rev_again] + expect(actual_operations_order).to eq(%w[deploy_to_previous_rev deploy_to_latest_rev deploy_to_previous_rev_again]) end it "is marked updated" do - deploy_to_previous_rev_again.should be_updated_by_last_action + expect(deploy_to_previous_rev_again).to be_updated_by_last_action end it "deploys the right code" do - IO.read(rel_path("current/app/app.rb")).should include("this is the third version of the app") + expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the third version of the app") end it "all_releases after first deploy should have one entry" do - @previous_rev_all_releases.length.should == 1 + expect(@previous_rev_all_releases.length).to eq(1) end it "all_releases after second deploy should have two entries" do - @latest_rev_all_releases.length.should == 2 + expect(@latest_rev_all_releases.length).to eq(2) end it "all_releases after rollback should have one entry" do - @previous_rev_again_all_releases.length.should == 1 + expect(@previous_rev_again_all_releases.length).to eq(1) end it "all_releases after rollback should be the same as after the first deploy" do - @previous_rev_again_all_releases.should == @previous_rev_all_releases + expect(@previous_rev_again_all_releases).to eq(@previous_rev_all_releases) end end @@ -438,23 +438,23 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:second_rev) it "restarts the application after rolling back" do - actual_operations_order.should == %w[deploy_to_second_rev deploy_to_previous_rev deploy_to_previous_rev_again deploy_to_latest_rev deploy_to_latest_rev_again] + expect(actual_operations_order).to eq(%w[deploy_to_second_rev deploy_to_previous_rev deploy_to_previous_rev_again deploy_to_latest_rev deploy_to_latest_rev_again]) end it "is marked updated" do - deploy_to_latest_rev_again.should be_updated_by_last_action + expect(deploy_to_latest_rev_again).to be_updated_by_last_action end it "deploys the right code" do - IO.read(rel_path("current/app/app.rb")).should include("this is the second version of the app") + expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the second version of the app") end it "all_releases after rollback should have one entry" do - @fifth_deploy_all_releases.length.should == 1 + expect(@fifth_deploy_all_releases.length).to eq(1) end it "all_releases after rollback should be the same as after the first deploy" do - @fifth_deploy_all_releases.should == @first_deploy_all_releases + expect(@fifth_deploy_all_releases).to eq(@first_deploy_all_releases) end end @@ -475,23 +475,23 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:second_rev) it "restarts the application after rolling back" do - actual_operations_order.should == %w[deploy_to_second_rev deploy_to_previous_rev deploy_to_second_rev_again deploy_to_latest_rev deploy_to_second_rev_again_again] + expect(actual_operations_order).to eq(%w[deploy_to_second_rev deploy_to_previous_rev deploy_to_second_rev_again deploy_to_latest_rev deploy_to_second_rev_again_again]) end it "is marked updated" do - deploy_to_second_rev_again_again.should be_updated_by_last_action + expect(deploy_to_second_rev_again_again).to be_updated_by_last_action end it "deploys the right code" do - IO.read(rel_path("current/app/app.rb")).should include("this is the second version of the app") + expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the second version of the app") end it "all_releases after rollback should have one entry" do - @fifth_deploy_all_releases.length.should == 1 + expect(@fifth_deploy_all_releases.length).to eq(1) end it "all_releases after rollback should be the same as after the first deploy" do - @fifth_deploy_all_releases.should == @first_deploy_all_releases + expect(@fifth_deploy_all_releases).to eq(@first_deploy_all_releases) end end @@ -510,21 +510,21 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end before do - File.should_not exist(deploy_directory) + expect(File).not_to exist(deploy_directory) deploy_to_latest_rev.run_action(:deploy) end it "creates the required directory tree" do - File.should be_directory(rel_path("releases")) - File.should be_directory(rel_path("shared")) - File.should be_directory(rel_path("releases/#{latest_rev}")) + expect(File).to be_directory(rel_path("releases")) + expect(File).to be_directory(rel_path("shared")) + expect(File).to be_directory(rel_path("releases/#{latest_rev}")) - File.should be_directory(rel_path("current/tmp")) - File.should be_directory(rel_path("current/config")) - File.should be_directory(rel_path("current/public")) + expect(File).to be_directory(rel_path("current/tmp")) + expect(File).to be_directory(rel_path("current/config")) + expect(File).to be_directory(rel_path("current/public")) - File.should be_symlink(rel_path("current")) - File.readlink(rel_path("current")).should == rel_path("releases/#{latest_rev}") + expect(File).to be_symlink(rel_path("current")) + expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}")) end the_app_is_deployed_at_revision(:latest_rev) @@ -599,18 +599,18 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:latest_rev) it "is marked updated" do - deploy_to_latest_with_inline_recipes.should be_updated_by_last_action + expect(deploy_to_latest_with_inline_recipes).to be_updated_by_last_action end it "calls the callbacks in order" do - callback_order.should == [:before_migrate, :before_symlink, :before_restart, :after_restart] + expect(callback_order).to eq([:before_migrate, :before_symlink, :before_restart, :after_restart]) end it "runs chef resources in the callbacks" do - File.should exist(rel_path("current/before_migrate.txt")) - File.should exist(rel_path("current/before_symlink.txt")) - File.should exist(rel_path("current/tmp/before_restart.txt")) - File.should exist(rel_path("current/tmp/after_restart.txt")) + expect(File).to exist(rel_path("current/before_migrate.txt")) + expect(File).to exist(rel_path("current/before_symlink.txt")) + expect(File).to exist(rel_path("current/tmp/before_restart.txt")) + expect(File).to exist(rel_path("current/tmp/after_restart.txt")) end end @@ -629,10 +629,10 @@ describe Chef::Resource::DeployRevision, :unix_only => true do the_app_is_deployed_at_revision(:rev_with_in_repo_callbacks) it "runs chef resources in the callbacks" do - File.should exist(rel_path("current/before_migrate.txt")) - File.should exist(rel_path("current/before_symlink.txt")) - File.should exist(rel_path("current/tmp/before_restart.txt")) - File.should exist(rel_path("current/tmp/after_restart.txt")) + expect(File).to exist(rel_path("current/before_migrate.txt")) + expect(File).to exist(rel_path("current/before_symlink.txt")) + expect(File).to exist(rel_path("current/tmp/before_restart.txt")) + expect(File).to exist(rel_path("current/tmp/after_restart.txt")) end end @@ -690,7 +690,7 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end it "runs migrations in between the before_migrate and before_symlink steps" do - actual_operations_order.should == %w[before_migrate migration before_symlink before_restart after_restart] + expect(actual_operations_order).to eq(%w[before_migrate migration before_symlink before_restart after_restart]) end end @@ -703,7 +703,7 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end it "should not raise an exception calling File.utime on symlinks" do - lambda { deploy_with_in_repo_symlinks.run_action(:deploy) }.should_not raise_error + expect { deploy_with_in_repo_symlinks.run_action(:deploy) }.not_to raise_error end end @@ -712,16 +712,16 @@ describe Chef::Resource::DeployRevision, :unix_only => true do shared_examples_for "a redeployed application" do it "should redeploy the application" do - File.should be_directory(rel_path("releases")) - File.should be_directory(rel_path("shared")) - File.should be_directory(rel_path("releases/#{latest_rev}")) + expect(File).to be_directory(rel_path("releases")) + expect(File).to be_directory(rel_path("shared")) + expect(File).to be_directory(rel_path("releases/#{latest_rev}")) - File.should be_directory(rel_path("current/tmp")) - File.should be_directory(rel_path("current/config")) - File.should be_directory(rel_path("current/public")) + expect(File).to be_directory(rel_path("current/tmp")) + expect(File).to be_directory(rel_path("current/config")) + expect(File).to be_directory(rel_path("current/public")) - File.should be_symlink(rel_path("current")) - File.readlink(rel_path("current")).should == rel_path("releases/#{latest_rev}") + expect(File).to be_symlink(rel_path("current")) + expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}")) end end @@ -758,23 +758,23 @@ describe Chef::Resource::DeployRevision, :unix_only => true do shared_examples_for "a recovered deployment" do it "should redeploy the application" do - File.should be_directory(rel_path("releases")) - File.should be_directory(rel_path("shared")) - File.should be_directory(rel_path("releases/#{latest_rev}")) + expect(File).to be_directory(rel_path("releases")) + expect(File).to be_directory(rel_path("shared")) + expect(File).to be_directory(rel_path("releases/#{latest_rev}")) - File.should be_directory(rel_path("current/tmp")) - File.should be_directory(rel_path("current/config")) - File.should be_directory(rel_path("current/public")) + expect(File).to be_directory(rel_path("current/tmp")) + expect(File).to be_directory(rel_path("current/config")) + expect(File).to be_directory(rel_path("current/public")) - File.should be_symlink(rel_path("current")) - File.readlink(rel_path("current")).should == rel_path("releases/#{latest_rev}") + expect(File).to be_symlink(rel_path("current")) + expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}")) # if callbacks ran, we know the app was deployed and not merely rolled # back to a (busted) prior deployment. - callback_order.should == [:before_migrate, + expect(callback_order).to eq([:before_migrate, :before_symlink, :before_restart, - :after_restart ] + :after_restart ]) end end @@ -794,7 +794,7 @@ describe Chef::Resource::DeployRevision, :unix_only => true do context "in the `#{callback}' callback" do before do - lambda { deploy_that_fails.run_action(:deploy) }.should raise_error(Exception, %r{I am a failed deploy}) + expect { deploy_that_fails.run_action(:deploy) }.to raise_error(Exception, %r{I am a failed deploy}) deploy_to_latest_with_callback_tracking.run_action(:deploy) end @@ -820,7 +820,7 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end before do - lambda { deploy_that_fails.run_action(:deploy) }.should raise_error(Chef::Exceptions::Exec) + expect { deploy_that_fails.run_action(:deploy) }.to raise_error(Chef::Exceptions::Exec) deploy_to_latest_with_callback_tracking.run_action(:deploy) end @@ -852,7 +852,7 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end before do - lambda { deploy_that_fails.run_action(:deploy) }.should raise_error(RuntimeError, /network error/) + expect { deploy_that_fails.run_action(:deploy) }.to raise_error(RuntimeError, /network error/) deploy_to_latest_with_callback_tracking.run_action(:deploy) end @@ -868,12 +868,12 @@ describe Chef::Resource::DeployRevision, :unix_only => true do end before do - lambda { deploy_that_fails.run_action(:deploy) }.should raise_error(Exception, %r{I am a failed deploy}) + expect { deploy_that_fails.run_action(:deploy) }.to raise_error(Exception, %r{I am a failed deploy}) deploy_to_latest_rev.run_action(:deploy) end it "removes the unsuccessful deploy after a later successful deploy" do - ::File.should_not exist(File.join(deploy_directory, "releases", previous_rev)) + expect(::File).not_to exist(File.join(deploy_directory, "releases", previous_rev)) end end diff --git a/spec/functional/resource/env_spec.rb b/spec/functional/resource/env_spec.rb index 8178eeba3d..16caec14bf 100755 --- a/spec/functional/resource/env_spec.rb +++ b/spec/functional/resource/env_spec.rb @@ -131,12 +131,12 @@ describe Chef::Resource::Env, :windows_only do let!(:env_path_before) { ENV['PATH'] } it 'should expand PATH' do - path_before.should_not include(env_val) + expect(path_before).not_to include(env_val) test_resource.key_name('PATH') test_resource.value("#{path_before};#{env_val}") test_resource.run_action(:create) - ENV['PATH'].should_not include(env_val) - ENV['PATH'].should include("#{random_name}") + expect(ENV['PATH']).not_to include(env_val) + expect(ENV['PATH']).to include("#{random_name}") end after(:each) do diff --git a/spec/functional/resource/execute_spec.rb b/spec/functional/resource/execute_spec.rb index ff358fe045..39fef76ab0 100644 --- a/spec/functional/resource/execute_spec.rb +++ b/spec/functional/resource/execute_spec.rb @@ -47,7 +47,7 @@ describe Chef::Resource::Execute do true end execute_resource.run_action(:run) - execute_resource.should be_updated_by_last_action + expect(execute_resource).to be_updated_by_last_action end end @@ -58,7 +58,7 @@ describe Chef::Resource::Execute do it "guard inherits :cwd from resource" do execute_resource.run_action(:run) - execute_resource.should be_updated_by_last_action + expect(execute_resource).to be_updated_by_last_action end end @@ -77,7 +77,7 @@ describe Chef::Resource::Execute do it "guard inherits :environment value from resource" do execute_resource.run_action(:run) - execute_resource.should be_updated_by_last_action + expect(execute_resource).to be_updated_by_last_action end describe "when guard sets additional values in the :environment" do @@ -91,7 +91,7 @@ describe Chef::Resource::Execute do it "guard sees merged value for in its ENV" do execute_resource.run_action(:run) - execute_resource.should be_updated_by_last_action + expect(execute_resource).to be_updated_by_last_action end end @@ -106,7 +106,7 @@ describe Chef::Resource::Execute do it "guard sees value from guard options in its ENV" do execute_resource.run_action(:run) - execute_resource.should be_updated_by_last_action + expect(execute_resource).to be_updated_by_last_action end end end diff --git a/spec/functional/resource/file_spec.rb b/spec/functional/resource/file_spec.rb index 83f051ea06..cf70c349fb 100644 --- a/spec/functional/resource/file_spec.rb +++ b/spec/functional/resource/file_spec.rb @@ -77,11 +77,11 @@ describe Chef::Resource::File do context "and the target file does not exist" do it "creates the file" do - File.should exist(path) + expect(File).to exist(path) end it "is marked updated by last action" do - resource_without_content.should be_updated_by_last_action + expect(resource_without_content).to be_updated_by_last_action end end end @@ -106,11 +106,11 @@ describe Chef::Resource::File do end it "it creates the file" do - File.should exist(path) + expect(File).to exist(path) end it "is marked updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end @@ -128,15 +128,15 @@ describe Chef::Resource::File do end it "updates the mtime of the file" do - File.stat(path).mtime.should > @expected_mtime + expect(File.stat(path).mtime).to be > @expected_mtime end it "does not change the content" do - sha256_checksum(path).should == @expected_checksum + expect(sha256_checksum(path)).to eq(@expected_checksum) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end end diff --git a/spec/functional/resource/git_spec.rb b/spec/functional/resource/git_spec.rb index f0bd94b0c0..4f462b7cb6 100644 --- a/spec/functional/resource/git_spec.rb +++ b/spec/functional/resource/git_spec.rb @@ -130,10 +130,10 @@ E it "checks out the revision pointed to by the tag commit, not the tag commit itself" do basic_git_resource.run_action(:sync) head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == v1_commit + expect(head_rev).to eq(v1_commit) # also verify the tag commit itself is what we expect as an extra sanity check rev = shell_out!('git rev-parse v1.0.0', :cwd => deploy_directory, :returns => [0]).stdout.strip - rev.should == v1_tag + expect(rev).to eq(v1_tag) end it "doesn't update if up-to-date" do @@ -141,10 +141,10 @@ E # properly to the pointed to commit. basic_git_resource.run_action(:sync) head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == v1_commit + expect(head_rev).to eq(v1_commit) copy_git_resource.run_action(:sync) - copy_git_resource.should_not be_updated + expect(copy_git_resource).not_to be_updated end end @@ -167,25 +167,25 @@ E basic_git_resource.revision rev_foo basic_git_resource.run_action(:sync) head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == rev_foo + expect(head_rev).to eq(rev_foo) end it "doesn't update if up-to-date" do basic_git_resource.revision rev_foo basic_git_resource.run_action(:sync) head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == rev_foo + expect(head_rev).to eq(rev_foo) copy_git_resource.revision rev_foo copy_git_resource.run_action(:sync) - copy_git_resource.should_not be_updated + expect(copy_git_resource).not_to be_updated end it "checks out the expected revision 972d" do basic_git_resource.revision rev_testing basic_git_resource.run_action(:sync) head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == rev_testing + expect(head_rev).to eq(rev_testing) end end @@ -200,7 +200,7 @@ E it "checks out the expected revision" do basic_git_resource.run_action(:sync) head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == rev_head + expect(head_rev).to eq(rev_head) end end @@ -215,7 +215,7 @@ E it "checks out HEAD as the default revision" do basic_git_resource.run_action(:sync) head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == rev_head + expect(head_rev).to eq(rev_head) end end @@ -244,7 +244,7 @@ E head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == rev_head + expect(head_rev).to eq(rev_head) end it "checks out the (master) HEAD revision when no revision is specified (ignores tag)" do @@ -252,7 +252,7 @@ E head_rev = shell_out!('git rev-parse HEAD', :cwd => deploy_directory, :returns => [0]).stdout.strip - head_rev.should == rev_head + expect(head_rev).to eq(rev_head) end end diff --git a/spec/functional/resource/group_spec.rb b/spec/functional/resource/group_spec.rb index 9c14232071..01e79f96bf 100644 --- a/spec/functional/resource/group_spec.rb +++ b/spec/functional/resource/group_spec.rb @@ -108,7 +108,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte temp_resource.append(true) temp_resource.run_action(:modify) members.each do |member| - user_exist_in_group?(member).should == true + expect(user_exist_in_group?(member)).to eq(true) end end @@ -119,7 +119,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte temp_resource.run_action(:create) group_should_exist(group_name) included_members.each do |member| - user_exist_in_group?(member).should == false + expect(user_exist_in_group?(member)).to eq(false) end end @@ -149,8 +149,8 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte it "should remove the existing users and add the new users to the group" do group_resource.run_action(tested_action) - user_exist_in_group?(spec_members[1]).should == true - user_exist_in_group?(spec_members[0]).should == false + expect(user_exist_in_group?(spec_members[1])).to eq(true) + expect(user_exist_in_group?(spec_members[0])).to eq(false) end end @@ -176,10 +176,10 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte group_resource.run_action(tested_action) included_members.each do |member| - user_exist_in_group?(member).should == true + expect(user_exist_in_group?(member)).to eq(true) end excluded_members.each do |member| - user_exist_in_group?(member).should == false + expect(user_exist_in_group?(member)).to eq(false) end end @@ -192,10 +192,10 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte group_resource.run_action(tested_action) included_members.each do |member| - user_exist_in_group?(member).should == true + expect(user_exist_in_group?(member)).to eq(true) end excluded_members.each do |member| - user_exist_in_group?(member).should == false + expect(user_exist_in_group?(member)).to eq(false) end end end @@ -204,13 +204,13 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte describe "when the users doesn't exist" do describe "when append is not set" do it "should raise an error" do - lambda { @grp_resource.run_action(tested_action) }.should raise_error + expect { @grp_resource.run_action(tested_action) }.to raise_error end end describe "when append is set" do it "should raise an error" do - lambda { @grp_resource.run_action(tested_action) }.should raise_error + expect { @grp_resource.run_action(tested_action) }.to raise_error end end end @@ -231,24 +231,24 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte describe "when updating membership" do it "raises an error for a non well-formed domain name" do group_resource.members [invalid_domain_user_name] - lambda { group_resource.run_action(tested_action) }.should raise_error Chef::Exceptions::Win32APIError + expect { group_resource.run_action(tested_action) }.to raise_error Chef::Exceptions::Win32APIError end it "raises an error for a nonexistent domain" do group_resource.members [nonexistent_domain_user_name] - lambda { group_resource.run_action(tested_action) }.should raise_error Chef::Exceptions::Win32APIError + expect { group_resource.run_action(tested_action) }.to raise_error Chef::Exceptions::Win32APIError end end describe "when removing members" do it "raises an error for a non well-formed domain name" do group_resource.excluded_members [invalid_domain_user_name] - lambda { group_resource.run_action(tested_action) }.should raise_error Chef::Exceptions::Win32APIError + expect { group_resource.run_action(tested_action) }.to raise_error Chef::Exceptions::Win32APIError end it "raises an error for a nonexistent domain" do group_resource.excluded_members [nonexistent_domain_user_name] - lambda { group_resource.run_action(tested_action) }.should raise_error Chef::Exceptions::Win32APIError + expect { group_resource.run_action(tested_action) }.to raise_error Chef::Exceptions::Win32APIError end end end @@ -264,7 +264,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte } it "append should be false by default" do - group_resource.append.should == false + expect(group_resource.append).to eq(false) end describe "group create action" do @@ -297,7 +297,7 @@ theoldmanwalkingdownthestreetalwayshadagoodsmileonhisfacetheoldmanwalking\ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } it "should not create a group" do - lambda { group_resource.run_action(:create) }.should raise_error + expect { group_resource.run_action(:create) }.to raise_error group_should_not_exist(group_name) end end @@ -308,7 +308,7 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } invalid_resource = group_resource.dup invalid_resource.members(["Jack"]) invalid_resource.excluded_members(["Jack"]) - lambda { invalid_resource.run_action(:create)}.should raise_error(Chef::Exceptions::ConflictingMembersInGroup) + expect { invalid_resource.run_action(:create)}.to raise_error(Chef::Exceptions::ConflictingMembersInGroup) end end end @@ -342,7 +342,7 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } describe "when there is no group" do it "should raise an error" do - lambda { group_resource.run_action(:modify) }.should raise_error + expect { group_resource.run_action(:modify) }.to raise_error end end @@ -370,11 +370,11 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } describe "when there is no group" do it "raises an error on modify" do - lambda { group_resource.run_action(:modify) }.should raise_error + expect { group_resource.run_action(:modify) }.to raise_error end it "does not raise an error on manage" do - lambda { group_resource.run_action(:manage) }.should_not raise_error + expect { group_resource.run_action(:manage) }.not_to raise_error end end @@ -399,15 +399,15 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } let(:excluded_members) { ["Anthony"] } it ":manage should raise an error" do - lambda {group_resource.run_action(:manage) }.should raise_error + expect {group_resource.run_action(:manage) }.to raise_error end it ":modify should raise an error" do - lambda {group_resource.run_action(:modify) }.should raise_error + expect {group_resource.run_action(:modify) }.to raise_error end it ":create should raise an error" do - lambda {group_resource.run_action(:create) }.should raise_error + expect {group_resource.run_action(:create) }.to raise_error end end @@ -419,11 +419,11 @@ downthestreetalwayshadagoodsmileonhisfacetheoldmanwalkingdownthestreeQQQQQQ" } end it ":manage should raise an error" do - lambda {group_resource.run_action(:manage) }.should raise_error + expect {group_resource.run_action(:manage) }.to raise_error end it ":modify should raise an error" do - lambda {group_resource.run_action(:modify) }.should raise_error + expect {group_resource.run_action(:modify) }.to raise_error end end end diff --git a/spec/functional/resource/ifconfig_spec.rb b/spec/functional/resource/ifconfig_spec.rb index c36288498b..9c613544ac 100644 --- a/spec/functional/resource/ifconfig_spec.rb +++ b/spec/functional/resource/ifconfig_spec.rb @@ -143,7 +143,7 @@ describe Chef::Resource::Ifconfig, :requires_root, :external => include_flag do end it "should disable interface (vip)" do new_resource.run_action(:disable) - new_resource.should be_updated_by_last_action + expect(new_resource).to be_updated_by_last_action interface_should_not_exists(network_interface_alias(en0_interface_for_test)) end end @@ -155,7 +155,7 @@ describe Chef::Resource::Ifconfig, :requires_root, :external => include_flag do end it "should delete interface (vip)" do new_resource.run_action(:delete) - new_resource.should be_updated_by_last_action + expect(new_resource).to be_updated_by_last_action interface_should_not_exists(network_interface_alias(en0_interface_for_test)) interface_persistence_should_not_exists(network_interface_alias(en0_interface_for_test)) end diff --git a/spec/functional/resource/link_spec.rb b/spec/functional/resource/link_spec.rb index 2220e973cf..b4c6412e5d 100644 --- a/spec/functional/resource/link_spec.rb +++ b/spec/functional/resource/link_spec.rb @@ -123,8 +123,8 @@ describe Chef::Resource::Link do describe "when supported on platform", :not_supported_on_win2k3 do shared_examples_for 'delete errors out' do it 'delete errors out' do - lambda { resource.run_action(:delete) }.should raise_error(Chef::Exceptions::Link) - (File.exist?(target_file) || symlink?(target_file)).should be_true + expect { resource.run_action(:delete) }.to raise_error(Chef::Exceptions::Link) + expect(File.exist?(target_file) || symlink?(target_file)).to be_truthy end end @@ -132,19 +132,19 @@ describe Chef::Resource::Link do describe 'the :delete action' do before(:each) do @info = [] - Chef::Log.stub(:info) { |msg| @info << msg } + allow(Chef::Log).to receive(:info) { |msg| @info << msg } resource.run_action(:delete) end it 'leaves the file deleted' do - File.exist?(target_file).should be_false - symlink?(target_file).should be_false + expect(File.exist?(target_file)).to be_falsey + expect(symlink?(target_file)).to be_falsey end it 'does not mark the resource updated' do - resource.should_not be_updated + expect(resource).not_to be_updated end it 'does not log that it deleted' do - @info.include?("link[#{target_file}] deleted").should be_false + expect(@info.include?("link[#{target_file}] deleted")).to be_falsey end end end @@ -153,19 +153,19 @@ describe Chef::Resource::Link do describe 'the :delete action' do before(:each) do @info = [] - Chef::Log.stub(:info) { |msg| @info << msg } + allow(Chef::Log).to receive(:info) { |msg| @info << msg } resource.run_action(:delete) end it 'deletes the file' do - File.exist?(target_file).should be_false - symlink?(target_file).should be_false + expect(File.exist?(target_file)).to be_falsey + expect(symlink?(target_file)).to be_falsey end it 'marks the resource updated' do - resource.should be_updated + expect(resource).to be_updated end it 'logs that it deleted' do - @info.include?("link[#{target_file}] deleted").should be_true + expect(@info.include?("link[#{target_file}] deleted")).to be_truthy end end end @@ -174,19 +174,19 @@ describe Chef::Resource::Link do describe 'the :create action' do before(:each) do @info = [] - Chef::Log.stub(:info) { |msg| @info << msg } + allow(Chef::Log).to receive(:info) { |msg| @info << msg } resource.run_action(:create) end it 'links to the target file' do - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), to).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), to)).to be_truthy end it 'marks the resource updated' do - resource.should be_updated + expect(resource).to be_updated end it 'logs that it created' do - @info.include?("link[#{target_file}] created").should be_true + expect(@info.include?("link[#{target_file}] created")).to be_truthy end end end @@ -195,19 +195,19 @@ describe Chef::Resource::Link do describe 'the :create action' do before(:each) do @info = [] - Chef::Log.stub(:info) { |msg| @info << msg } + allow(Chef::Log).to receive(:info) { |msg| @info << msg } resource.run_action(:create) end it 'leaves the file linked' do - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), to).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), to)).to be_truthy end it 'does not mark the resource updated' do - resource.should_not be_updated + expect(resource).not_to be_updated end it 'does not log that it created' do - @info.include?("link[#{target_file}] created").should be_false + expect(@info.include?("link[#{target_file}] created")).to be_falsey end end end @@ -216,23 +216,23 @@ describe Chef::Resource::Link do describe 'the :create action' do before(:each) do @info = [] - Chef::Log.stub(:info) { |msg| @info << msg } + allow(Chef::Log).to receive(:info) { |msg| @info << msg } resource.run_action(:create) end it 'preserves the hard link' do - File.exists?(target_file).should be_true - symlink?(target_file).should be_false + expect(File.exists?(target_file)).to be_truthy + expect(symlink?(target_file)).to be_falsey # Writing to one hardlinked file should cause both # to have the new value. - IO.read(to).should == IO.read(target_file) + expect(IO.read(to)).to eq(IO.read(target_file)) File.open(to, "w") { |file| file.write('wowzers') } - IO.read(target_file).should == 'wowzers' + expect(IO.read(target_file)).to eq('wowzers') end it 'marks the resource updated' do - resource.should be_updated + expect(resource).to be_updated end it 'logs that it created' do - @info.include?("link[#{target_file}] created").should be_true + expect(@info.include?("link[#{target_file}] created")).to be_truthy end end end @@ -241,23 +241,23 @@ describe Chef::Resource::Link do describe 'the :create action' do before(:each) do @info = [] - Chef::Log.stub(:info) { |msg| @info << msg } + allow(Chef::Log).to receive(:info) { |msg| @info << msg } resource.run_action(:create) end it 'links to the target file' do - File.exists?(target_file).should be_true - symlink?(target_file).should be_false + expect(File.exists?(target_file)).to be_truthy + expect(symlink?(target_file)).to be_falsey # Writing to one hardlinked file should cause both # to have the new value. - IO.read(to).should == IO.read(target_file) + expect(IO.read(to)).to eq(IO.read(target_file)) File.open(to, "w") { |file| file.write('wowzers') } - IO.read(target_file).should == 'wowzers' + expect(IO.read(target_file)).to eq('wowzers') end it 'does not mark the resource updated' do - resource.should_not be_updated + expect(resource).not_to be_updated end it 'does not log that it created' do - @info.include?("link[#{target_file}] created").should be_false + expect(@info.include?("link[#{target_file}] created")).to be_falsey end end end @@ -278,14 +278,14 @@ describe Chef::Resource::Link do context 'pointing at the target' do before(:each) do symlink(to, target_file) - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), to).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), to)).to be_truthy end include_context 'create symbolic link is noop' include_context 'delete succeeds' it 'the :delete action does not delete the target file' do resource.run_action(:delete) - File.exists?(to).should be_true + expect(File.exists?(to)).to be_truthy end end context 'pointing somewhere else' do @@ -293,8 +293,8 @@ describe Chef::Resource::Link do @other_target = File.join(test_file_dir, make_tmpname('other_spec')) File.open(@other_target, 'w') { |file| file.write('eek') } symlink(@other_target, target_file) - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), @other_target).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), @other_target)).to be_truthy end after(:each) do File.delete(@other_target) @@ -303,15 +303,15 @@ describe Chef::Resource::Link do include_context 'delete succeeds' it 'the :delete action does not delete the target file' do resource.run_action(:delete) - File.exists?(to).should be_true + expect(File.exists?(to)).to be_truthy end end context 'pointing nowhere' do before(:each) do nonexistent = File.join(test_file_dir, make_tmpname('nonexistent_spec')) symlink(nonexistent, target_file) - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), nonexistent).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), nonexistent)).to be_truthy end include_context 'create symbolic link succeeds' include_context 'delete succeeds' @@ -320,8 +320,8 @@ describe Chef::Resource::Link do context 'and the link already exists and is a hard link to the file' do before(:each) do link(to, target_file) - File.exists?(target_file).should be_true - symlink?(target_file).should be_false + expect(File.exists?(target_file)).to be_truthy + expect(symlink?(target_file)).to be_falsey end include_context 'create symbolic link succeeds' it_behaves_like 'delete errors out' @@ -339,16 +339,16 @@ describe Chef::Resource::Link do end it 'create errors out' do if windows? - lambda { resource.run_action(:create) }.should raise_error(Errno::EACCES) + expect { resource.run_action(:create) }.to raise_error(Errno::EACCES) elsif os_x? or solaris? or freebsd? or aix? - lambda { resource.run_action(:create) }.should raise_error(Errno::EPERM) + expect { resource.run_action(:create) }.to raise_error(Errno::EPERM) else - lambda { resource.run_action(:create) }.should raise_error(Errno::EISDIR) + expect { resource.run_action(:create) }.to raise_error(Errno::EISDIR) end end it_behaves_like 'delete errors out' end - context 'and the link already exists and is not writeable to this user', :pending do + context 'and the link already exists and is not writeable to this user', :skip => true do end it_behaves_like 'a securable resource without existing target' do let(:path) { target_file } @@ -392,8 +392,8 @@ describe Chef::Resource::Link do @other_target = File.join(test_file_dir, make_tmpname("other_spec")) File.open(@other_target, "w") { |file| file.write("eek") } symlink(@other_target, to) - symlink?(to).should be_true - paths_eql?(readlink(to), @other_target).should be_true + expect(symlink?(to)).to be_truthy + expect(paths_eql?(readlink(to), @other_target)).to be_truthy end after(:each) do File.delete(@other_target) @@ -407,8 +407,8 @@ describe Chef::Resource::Link do before(:each) do @other_target = File.join(test_file_dir, make_tmpname("other_spec")) symlink(@other_target, to) - symlink?(to).should be_true - paths_eql?(readlink(to), @other_target).should be_true + expect(symlink?(to)).to be_truthy + expect(paths_eql?(readlink(to), @other_target)).to be_truthy end context 'and the link does not yet exist' do include_context 'create symbolic link succeeds' @@ -416,7 +416,7 @@ describe Chef::Resource::Link do end end end - context "when the link destination is not readable to this user", :pending do + context "when the link destination is not readable to this user", :skip => true do end context "when the link destination does not exist" do include_context 'create symbolic link succeeds' @@ -440,8 +440,8 @@ describe Chef::Resource::Link do context 'when the link already exists and points at the target' do before(:each) do symlink(to, target_file) - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), to).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), to)).to be_truthy end include_context 'create symbolic link is noop' include_context 'delete succeeds' @@ -449,8 +449,8 @@ describe Chef::Resource::Link do context 'when the link already exists and points at the target with an absolute path' do before(:each) do symlink(absolute_to, target_file) - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), absolute_to).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), absolute_to)).to be_truthy end include_context 'create symbolic link succeeds' include_context 'delete succeeds' @@ -477,8 +477,8 @@ describe Chef::Resource::Link do context "and the link already exists and is a symbolic link pointing at the same file" do before(:each) do symlink(to, target_file) - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), to).should be_true + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), to)).to be_truthy end include_context 'create hard link succeeds' it_behaves_like 'delete errors out' @@ -486,14 +486,14 @@ describe Chef::Resource::Link do context 'and the link already exists and is a hard link to the file' do before(:each) do link(to, target_file) - File.exists?(target_file).should be_true - symlink?(target_file).should be_false + expect(File.exists?(target_file)).to be_truthy + expect(symlink?(target_file)).to be_falsey end include_context 'create hard link is noop' include_context 'delete succeeds' it 'the :delete action does not delete the target file' do resource.run_action(:delete) - File.exists?(to).should be_true + expect(File.exists?(to)).to be_truthy end end context "and the link already exists and is a file" do @@ -509,16 +509,16 @@ describe Chef::Resource::Link do end it 'errors out' do if windows? - lambda { resource.run_action(:create) }.should raise_error(Errno::EACCES) + expect { resource.run_action(:create) }.to raise_error(Errno::EACCES) elsif os_x? or solaris? or freebsd? or aix? - lambda { resource.run_action(:create) }.should raise_error(Errno::EPERM) + expect { resource.run_action(:create) }.to raise_error(Errno::EPERM) else - lambda { resource.run_action(:create) }.should raise_error(Errno::EISDIR) + expect { resource.run_action(:create) }.to raise_error(Errno::EISDIR) end end it_behaves_like 'delete errors out' end - context "and the link already exists and is not writeable to this user", :pending do + context "and the link already exists and is not writeable to this user", :skip => true do end context "and specifies security attributes" do before(:each) do @@ -527,9 +527,9 @@ describe Chef::Resource::Link do it 'ignores them' do resource.run_action(:create) if windows? - Chef::ReservedNames::Win32::Security.get_named_security_info(target_file).owner.should_not == SID.Guest + expect(Chef::ReservedNames::Win32::Security.get_named_security_info(target_file).owner).not_to eq(SID.Guest) else - File.lstat(target_file).uid.should_not == Etc.getpwnam('nobody').uid + expect(File.lstat(target_file).uid).not_to eq(Etc.getpwnam('nobody').uid) end end end @@ -540,7 +540,7 @@ describe Chef::Resource::Link do end context 'and the link does not yet exist' do it 'create errors out' do - lambda { resource.run_action(:create) }.should raise_error(windows? ? Chef::Exceptions::Win32APIError : Errno::EPERM) + expect { resource.run_action(:create) }.to raise_error(windows? ? Chef::Exceptions::Win32APIError : Errno::EPERM) end include_context 'delete is noop' end @@ -551,8 +551,8 @@ describe Chef::Resource::Link do @other_target = File.join(test_file_dir, make_tmpname("other_spec")) File.open(@other_target, "w") { |file| file.write("eek") } symlink(@other_target, to) - symlink?(to).should be_true - paths_eql?(readlink(to), @other_target).should be_true + expect(symlink?(to)).to be_truthy + expect(paths_eql?(readlink(to), @other_target)).to be_truthy end after(:each) do File.delete(@other_target) @@ -560,12 +560,11 @@ describe Chef::Resource::Link do context 'and the link does not yet exist' do it 'links to the target file' do resource.run_action(:create) - File.exists?(target_file).should be_true + expect(File.exists?(target_file)).to be_truthy # OS X gets angry about this sort of link. Bug in OS X, IMO. - pending('OS X/FreeBSD/AIX symlink? and readlink working on hard links to symlinks', :if => (os_x? or freebsd? or aix?)) do - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), @other_target).should be_true - end + pending('OS X/FreeBSD/AIX symlink? and readlink working on hard links to symlinks') if (os_x? or freebsd? or aix?) + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), @other_target)).to be_truthy end include_context 'delete is noop' end @@ -574,33 +573,32 @@ describe Chef::Resource::Link do before(:each) do @other_target = File.join(test_file_dir, make_tmpname("other_spec")) symlink(@other_target, to) - symlink?(to).should be_true - paths_eql?(readlink(to), @other_target).should be_true + expect(symlink?(to)).to be_truthy + expect(paths_eql?(readlink(to), @other_target)).to be_truthy end context 'and the link does not yet exist' do it 'links to the target file' do - pending('OS X/FreeBSD/AIX fails to create hardlinks to broken symlinks', :if => (os_x? or freebsd? or aix?)) do - resource.run_action(:create) - # Windows and Unix have different definitions of exists? here, and that's OK. - if windows? - File.exists?(target_file).should be_true - else - File.exists?(target_file).should be_false - end - symlink?(target_file).should be_true - paths_eql?(readlink(target_file), @other_target).should be_true + pending('OS X/FreeBSD/AIX fails to create hardlinks to broken symlinks') if (os_x? or freebsd? or aix?) + resource.run_action(:create) + # Windows and Unix have different definitions of exists? here, and that's OK. + if windows? + expect(File.exists?(target_file)).to be_truthy + else + expect(File.exists?(target_file)).to be_falsey end + expect(symlink?(target_file)).to be_truthy + expect(paths_eql?(readlink(target_file), @other_target)).to be_truthy end include_context 'delete is noop' end end end - context "when the link destination is not readable to this user", :pending do + context "when the link destination is not readable to this user", :skip => true do end context "when the link destination does not exist" do context 'and the link does not yet exist' do it 'create errors out' do - lambda { resource.run_action(:create) }.should raise_error(Errno::ENOENT) + expect { resource.run_action(:create) }.to raise_error(Errno::ENOENT) end include_context 'delete is noop' end @@ -610,7 +608,7 @@ describe Chef::Resource::Link do describe "when not supported on platform", :win2k3_only do it "raises error" do - lambda {resource}.should raise_error(Chef::Exceptions::Win32APIFunctionNotImplemented) + expect {resource}.to raise_error(Chef::Exceptions::Win32APIFunctionNotImplemented) end end end diff --git a/spec/functional/resource/mount_spec.rb b/spec/functional/resource/mount_spec.rb index 962c02670c..a016d12293 100644 --- a/spec/functional/resource/mount_spec.rb +++ b/spec/functional/resource/mount_spec.rb @@ -82,7 +82,7 @@ describe Chef::Resource::Mount, :requires_root, :external => include_flag do end def mount_should_not_exists(mount_point) - shell_out("mount").stdout.should_not include(mount_point) + expect(shell_out("mount").stdout).not_to include(mount_point) end def unix_mount_config_file @@ -106,7 +106,7 @@ describe Chef::Resource::Mount, :requires_root, :external => include_flag do end def mount_should_be_disabled(mount_point) - shell_out("cat #{unix_mount_config_file}").stdout.should_not include("#{mount_point}:") + expect(shell_out("cat #{unix_mount_config_file}").stdout).not_to include("#{mount_point}:") end let(:new_resource) do @@ -155,10 +155,10 @@ describe Chef::Resource::Mount, :requires_root, :external => include_flag do describe "when the target state is a mounted filesystem" do it "should mount the filesystem if it isn't mounted" do - current_resource.enabled.should be_false - current_resource.mounted.should be_false + expect(current_resource.enabled).to be_falsey + expect(current_resource.mounted).to be_falsey new_resource.run_action(:mount) - new_resource.should be_updated + expect(new_resource).to be_updated mount_should_exist(new_resource.mount_point, new_resource.device) end end diff --git a/spec/functional/resource/ohai_spec.rb b/spec/functional/resource/ohai_spec.rb index b1e4891293..da47b9e140 100644 --- a/spec/functional/resource/ohai_spec.rb +++ b/spec/functional/resource/ohai_spec.rb @@ -42,7 +42,7 @@ describe Chef::Resource::Ohai do sleep 1 ohai_resource.run_action(:reload) - node[:uptime].should_not == initial_uptime + expect(node[:uptime]).not_to eq(initial_uptime) end end diff --git a/spec/functional/resource/package_spec.rb b/spec/functional/resource/package_spec.rb index 548db40e79..5c17ca0107 100644 --- a/spec/functional/resource/package_spec.rb +++ b/spec/functional/resource/package_spec.rb @@ -159,25 +159,25 @@ describe Chef::Resource::Package, metadata do it "installs the package with action :install" do package_resource.run_action(:install) shell_out!("dpkg -l chef-integration-test") - package_resource.should be_updated_by_last_action + expect(package_resource).to be_updated_by_last_action end it "installs the package for action :upgrade" do package_resource.run_action(:upgrade) shell_out!("dpkg -l chef-integration-test") - package_resource.should be_updated_by_last_action + expect(package_resource).to be_updated_by_last_action end it "does nothing for action :remove" do package_resource.run_action(:remove) shell_out!("dpkg -l chef-integration-test", :returns => [1]) - package_resource.should_not be_updated_by_last_action + expect(package_resource).not_to be_updated_by_last_action end it "does nothing for action :purge" do package_resource.run_action(:purge) shell_out!("dpkg -l chef-integration-test", :returns => [1]) - package_resource.should_not be_updated_by_last_action + expect(package_resource).not_to be_updated_by_last_action end context "and a not-available package version is specified" do @@ -221,8 +221,8 @@ describe Chef::Resource::Package, metadata do it "preseeds the package, then installs it" do package_resource.run_action(:install) cmd = shell_out!("debconf-show chef-integration-test") - cmd.stdout.should include('chef-integration-test/sample-var: "hello world"') - package_resource.should be_updated_by_last_action + expect(cmd.stdout).to include('chef-integration-test/sample-var: "hello world"') + expect(package_resource).to be_updated_by_last_action end context "and the preseed file exists and is up-to-date" do @@ -239,8 +239,8 @@ describe Chef::Resource::Package, metadata do it "does not update the package configuration" do package_resource.run_action(:install) cmd = shell_out!("debconf-show chef-integration-test") - cmd.stdout.should include('chef-integration-test/sample-var: INVALID') - package_resource.should be_updated_by_last_action + expect(cmd.stdout).to include('chef-integration-test/sample-var: INVALID') + expect(package_resource).to be_updated_by_last_action end end @@ -267,8 +267,8 @@ describe Chef::Resource::Package, metadata do it "preseeds the package, then installs it" do package_resource.run_action(:install) cmd = shell_out!("debconf-show chef-integration-test") - cmd.stdout.should include('chef-integration-test/sample-var: "FROM TEMPLATE"') - package_resource.should be_updated_by_last_action + expect(cmd.stdout).to include('chef-integration-test/sample-var: "FROM TEMPLATE"') + expect(package_resource).to be_updated_by_last_action end context "with variables" do @@ -283,8 +283,8 @@ describe Chef::Resource::Package, metadata do it "preseeds the package, then installs it" do package_resource.run_action(:install) cmd = shell_out!("debconf-show chef-integration-test") - cmd.stdout.should include('chef-integration-test/sample-var: "SUPPORTS VARIABLES"') - package_resource.should be_updated_by_last_action + expect(cmd.stdout).to include('chef-integration-test/sample-var: "SUPPORTS VARIABLES"') + expect(package_resource).to be_updated_by_last_action end end @@ -302,13 +302,13 @@ describe Chef::Resource::Package, metadata do it "does nothing for action :install" do package_resource.run_action(:install) shell_out!("dpkg -l chef-integration-test", :returns => [0]) - package_resource.should_not be_updated_by_last_action + expect(package_resource).not_to be_updated_by_last_action end it "does nothing for action :upgrade" do package_resource.run_action(:upgrade) shell_out!("dpkg -l chef-integration-test", :returns => [0]) - package_resource.should_not be_updated_by_last_action + expect(package_resource).not_to be_updated_by_last_action end # Verify that the package is removed by running `dpkg -l PACKAGE` @@ -328,7 +328,7 @@ describe Chef::Resource::Package, metadata do pkg_check = shell_out!("dpkg -l chef-integration-test", :returns => [0,1]) if pkg_check.exitstatus == 0 - pkg_check.stdout.should =~ /un[\s]+chef-integration-test/ + expect(pkg_check.stdout).to match(/un[\s]+chef-integration-test/) end end @@ -336,13 +336,13 @@ describe Chef::Resource::Package, metadata do it "removes the package for action :remove" do package_resource.run_action(:remove) pkg_should_be_removed - package_resource.should be_updated_by_last_action + expect(package_resource).to be_updated_by_last_action end it "removes the package for action :purge" do package_resource.run_action(:purge) pkg_should_be_removed - package_resource.should be_updated_by_last_action + expect(package_resource).to be_updated_by_last_action end end @@ -356,14 +356,14 @@ describe Chef::Resource::Package, metadata do it "does nothing for action :install" do package_resource.run_action(:install) shell_out!("dpkg -l chef-integration-test", :returns => [0]) - package_resource.should_not be_updated_by_last_action + expect(package_resource).not_to be_updated_by_last_action end it "upgrades the package for action :upgrade" do package_resource.run_action(:upgrade) dpkg_l = shell_out!("dpkg -l chef-integration-test", :returns => [0]) - dpkg_l.stdout.should =~ /chef\-integration\-test[\s]+1\.1\-1/ - package_resource.should be_updated_by_last_action + expect(dpkg_l.stdout).to match(/chef\-integration\-test[\s]+1\.1\-1/) + expect(package_resource).to be_updated_by_last_action end context "and the resource specifies the new version" do @@ -376,8 +376,8 @@ describe Chef::Resource::Package, metadata do it "upgrades the package for action :install" do package_resource.run_action(:install) dpkg_l = shell_out!("dpkg -l chef-integration-test", :returns => [0]) - dpkg_l.stdout.should =~ /chef\-integration\-test[\s]+1\.1\-1/ - package_resource.should be_updated_by_last_action + expect(dpkg_l.stdout).to match(/chef\-integration\-test[\s]+1\.1\-1/) + expect(package_resource).to be_updated_by_last_action end end diff --git a/spec/functional/resource/powershell_spec.rb b/spec/functional/resource/powershell_spec.rb index e1e9f787a3..033f34e256 100644 --- a/spec/functional/resource/powershell_spec.rb +++ b/spec/functional/resource/powershell_spec.rb @@ -153,7 +153,7 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do detected_64_bit = source_contains_case_insensitive_content?( get_script_output, 'AMD64' ) - is_64_bit.should == detected_64_bit + expect(is_64_bit).to eq(detected_64_bit) end it "returns 1 if an invalid flag is passed to the interpreter" do @@ -186,12 +186,12 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do resource.returns(0) resource.run_action(:run) - source_contains_case_insensitive_content?( get_script_output, 'x86' ).should == true + expect(source_contains_case_insensitive_content?( get_script_output, 'x86' )).to eq(true) end it "raises an exception if :x86_64 process architecture is specified" do begin - resource.architecture(:x86_64).should raise_error Chef::Exceptions::Win32ArchitectureIncorrect + expect(resource.architecture(:x86_64)).to raise_error Chef::Exceptions::Win32ArchitectureIncorrect rescue Chef::Exceptions::Win32ArchitectureIncorrect end end @@ -204,7 +204,7 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do resource.returns(0) resource.run_action(:run) - source_contains_case_insensitive_content?( get_script_output, 'AMD64' ).should == true + expect(source_contains_case_insensitive_content?( get_script_output, 'AMD64' )).to eq(true) end it "executes a script with a 32-bit process if :i386 arch is specified" do @@ -213,7 +213,7 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do resource.returns(0) resource.run_action(:run) - source_contains_case_insensitive_content?( get_script_output, 'x86' ).should == true + expect(source_contains_case_insensitive_content?( get_script_output, 'x86' )).to eq(true) end end @@ -230,22 +230,22 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do it "evaluates a succeeding not_if block using cmd.exe as false by default" do resource.not_if "exit /b 0" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a failing not_if block using cmd.exe as true by default" do resource.not_if "exit /b 2" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates an succeeding only_if block using cmd.exe as true by default" do resource.only_if "exit /b 0" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a failing only_if block using cmd.exe as false by default" do resource.only_if "exit /b 2" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end end @@ -257,7 +257,7 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do it "evaluates a powershell $true for a only_if block as true" do resource.only_if "$true" resource.guard_interpreter :powershell_script - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end end @@ -269,184 +269,184 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do it "evaluates a powershell $false for a not_if block as true" do resource.not_if "$false" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a powershell $true for a not_if block as false" do resource.not_if "$true" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a powershell $false for an only_if block as false" do resource.only_if "$false" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a powershell $true for a only_if block as true" do resource.only_if "$true" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a not_if block using powershell.exe" do resource.not_if "exit([int32](![System.Environment]::CommandLine.Contains('powershell.exe')))" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates an only_if block using powershell.exe" do resource.only_if "exit([int32](![System.Environment]::CommandLine.Contains('powershell.exe')))" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a non-zero powershell exit status for not_if as true" do resource.not_if "exit 37" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a zero powershell exit status for not_if as false" do resource.not_if "exit 0" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a failed executable exit status for not_if as false" do resource.not_if windows_process_exit_code_not_found_content - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a successful executable exit status for not_if as true" do resource.not_if windows_process_exit_code_success_content - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a failed executable exit status for only_if as false" do resource.only_if windows_process_exit_code_not_found_content - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a successful executable exit status for only_if as true" do resource.only_if windows_process_exit_code_success_content - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a failed cmdlet exit status for not_if as true" do resource.not_if "throw 'up'" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a successful cmdlet exit status for not_if as true" do resource.not_if "cd ." - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a failed cmdlet exit status for only_if as false" do resource.only_if "throw 'up'" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a successful cmdlet exit status for only_if as true" do resource.only_if "cd ." - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a not_if block using the cwd guard parameter" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", :cwd => custom_cwd - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates an only_if block using the cwd guard parameter" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')", :cwd => custom_cwd - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "inherits cwd from the parent resource for only_if" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" resource.cwd custom_cwd resource.only_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "inherits cwd from the parent resource for not_if" do custom_cwd = "#{ENV['SystemRoot']}\\system32\\drivers\\etc" resource.cwd custom_cwd resource.not_if "exit ! [int32]($pwd.path -eq '#{custom_cwd}')" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 64-bit resource with a 64-bit guard and interprets boolean false as zero status code", :windows64_only do resource.architecture :x86_64 resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -ne 'AMD64')" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a 64-bit resource with a 64-bit guard and interprets boolean true as nonzero status code", :windows64_only do resource.architecture :x86_64 resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -eq 'AMD64')" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean false as zero status code" do resource.architecture :i386 resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -ne 'X86')" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean true as nonzero status code" do resource.architecture :i386 resource.only_if "exit [int32]($env:PROCESSOR_ARCHITECTURE -eq 'X86')" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a simple boolean false as nonzero status code when convert_boolean_return is true for only_if" do resource.convert_boolean_return true resource.only_if "$false" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a simple boolean false as nonzero status code when convert_boolean_return is true for not_if" do resource.convert_boolean_return true resource.not_if "$false" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a simple boolean true as 0 status code when convert_boolean_return is true for only_if" do resource.convert_boolean_return true resource.only_if "$true" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a simple boolean true as 0 status code when convert_boolean_return is true for not_if" do resource.convert_boolean_return true resource.not_if "$true" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean false as zero status code using convert_boolean_return for only_if" do resource.convert_boolean_return true resource.architecture :i386 resource.only_if "$env:PROCESSOR_ARCHITECTURE -eq 'X86'" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean false as zero status code using convert_boolean_return for not_if" do resource.convert_boolean_return true resource.architecture :i386 resource.not_if "$env:PROCESSOR_ARCHITECTURE -ne 'X86'" - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean true as nonzero status code using convert_boolean_return for only_if" do resource.convert_boolean_return true resource.architecture :i386 resource.only_if "$env:PROCESSOR_ARCHITECTURE -ne 'X86'" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end it "evaluates a 32-bit resource with a 32-bit guard and interprets boolean true as nonzero status code using convert_boolean_return for not_if" do resource.convert_boolean_return true resource.architecture :i386 resource.not_if "$env:PROCESSOR_ARCHITECTURE -eq 'X86'" - resource.should_skip?(:run).should be_true + expect(resource.should_skip?(:run)).to be_truthy end end end diff --git a/spec/functional/resource/reboot_spec.rb b/spec/functional/resource/reboot_spec.rb index 735ca994c8..99de136827 100644 --- a/spec/functional/resource/reboot_spec.rb +++ b/spec/functional/resource/reboot_spec.rb @@ -50,7 +50,7 @@ describe Chef::Resource::Reboot do expect(reboot_info[:reason]).to eq(expected[:reason]) expect(reboot_info[:requested_by]).to eq(expected[:requested_by]) - expect(resource.run_context.reboot_requested?).to be_true + expect(resource.run_context.reboot_requested?).to be_truthy end end @@ -97,7 +97,7 @@ describe Chef::Resource::Reboot do it 'should have cleared the reboot request' do # arguably we shouldn't be querying RunContext's internal data directly. expect(resource.run_context.reboot_info).to eq({}) - expect(resource.run_context.reboot_requested?).to be_false + expect(resource.run_context.reboot_requested?).to be_falsey end end end diff --git a/spec/functional/resource/registry_spec.rb b/spec/functional/resource/registry_spec.rb index 2d24eee6a3..d3120ac77c 100644 --- a/spec/functional/resource/registry_spec.rb +++ b/spec/functional/resource/registry_spec.rb @@ -35,12 +35,12 @@ describe Chef::Resource::RegistryKey, :unix_only do it "throws an exception because you don't have a windows registry (derp)" do @resource.key("HKCU\\Software\\Opscode") @resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) - lambda{@resource.run_action(:create)}.should raise_error(Chef::Exceptions::Win32NotWindows) + expect{@resource.run_action(:create)}.to raise_error(Chef::Exceptions::Win32NotWindows) end end end -describe Chef::Resource::RegistryKey, :windows_only do +describe Chef::Resource::RegistryKey, :windows_only, :pending => "Refactor helper methods" do # parent and key must be single keys, not paths let(:parent) { 'Opscode' } @@ -112,9 +112,9 @@ describe Chef::Resource::RegistryKey, :windows_only do @node.name("windowsbox") @rest_client = double("Chef::REST (mock)") - @rest_client.stub(:create_url).and_return("reports/nodes/windowsbox/runs/#{@run_id}"); - @rest_client.stub(:raw_http_request).and_return({"result"=>"ok"}); - @rest_client.stub(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/windowsbox/runs/#{@run_id}"}); + allow(@rest_client).to receive(:create_url).and_return("reports/nodes/windowsbox/runs/#{@run_id}"); + allow(@rest_client).to receive(:raw_http_request).and_return({"result"=>"ok"}); + allow(@rest_client).to receive(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/windowsbox/runs/#{@run_id}"}); @resource_reporter = Chef::ResourceReporter.new(@rest_client) @events.register(@resource_reporter) @@ -125,7 +125,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.cookbook_name = "monkey" @cookbook_version = double("Cookbook::Version", :version => "1.2.3") - @new_resource.stub(:cookbook_version).and_return(@cookbook_version) + allow(@new_resource).to receive(:cookbook_version).and_return(@cookbook_version) end after (:all) do @@ -141,8 +141,8 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) @new_resource.run_action(:create) - @registry.key_exists?(reg_child).should == true - @registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"}).should == true + expect(@registry.key_exists?(reg_child)).to eq(true) + expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) end it "does not create the key if it already exists with same value, type and data" do @@ -150,8 +150,8 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) @new_resource.run_action(:create) - @registry.key_exists?(reg_child).should == true - @registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"}).should == true + expect(@registry.key_exists?(reg_child)).to eq(true) + expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) end it "creates a value if it does not exist" do @@ -159,7 +159,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Mango", :type=>:string, :data=>"Yellow"}]) @new_resource.run_action(:create) - @registry.data_exists?(reg_child, {:name=>"Mango", :type=>:string, :data=>"Yellow"}).should == true + expect(@registry.data_exists?(reg_child, {:name=>"Mango", :type=>:string, :data=>"Yellow"})).to eq(true) end it "modifies the data if the key and value exist and type matches" do @@ -167,7 +167,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Not just Orange - OpscodeOrange!"}]) @new_resource.run_action(:create) - @registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Not just Orange - OpscodeOrange!"}).should == true + expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Not just Orange - OpscodeOrange!"})).to eq(true) end it "modifys the type if the key and value exist and the type does not match" do @@ -175,7 +175,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Color", :type=>:multi_string, :data=>["Not just Orange - OpscodeOrange!"]}]) @new_resource.run_action(:create) - @registry.data_exists?(reg_child, {:name=>"Color", :type=>:multi_string, :data=>["Not just Orange - OpscodeOrange!"]}).should == true + expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:multi_string, :data=>["Not just Orange - OpscodeOrange!"]})).to eq(true) end it "creates subkey if parent exists" do @@ -184,15 +184,15 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(false) @new_resource.run_action(:create) - @registry.key_exists?(reg_child + '\OpscodeTest').should == true - @registry.value_exists?(reg_child + '\OpscodeTest', {:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]}).should == true + expect(@registry.key_exists?(reg_child + '\OpscodeTest')).to eq(true) + expect(@registry.value_exists?(reg_child + '\OpscodeTest', {:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]})).to eq(true) end it "gives error if action create and parent does not exist and recursive is set to false" do @new_resource.key(reg_child + '\Missing1\Missing2') @new_resource.values([{:name=>"OC", :type=>:string, :data=>"MissingData"}]) @new_resource.recursive(false) - lambda{@new_resource.run_action(:create)}.should raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect{@new_resource.run_action(:create)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "creates missing keys if action create and parent does not exist and recursive is set to true" do @@ -201,8 +201,8 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(true) @new_resource.run_action(:create) - @registry.key_exists?(reg_child + '\Missing1\Missing2').should == true - @registry.value_exists?(reg_child + '\Missing1\Missing2', {:name=>"OC", :type=>:string, :data=>"MissingData"}).should == true + expect(@registry.key_exists?(reg_child + '\Missing1\Missing2')).to eq(true) + expect(@registry.value_exists?(reg_child + '\Missing1\Missing2', {:name=>"OC", :type=>:string, :data=>"MissingData"})).to eq(true) end it "creates key with multiple value as specified" do @@ -212,7 +212,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.run_action(:create) @new_resource.values.each do |value| - @registry.value_exists?(reg_child, value).should == true + expect(@registry.value_exists?(reg_child, value)).to eq(true) end end @@ -231,9 +231,9 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.architecture(:i386) @new_resource.run_action(:create) @registry.architecture = :i386 - @registry.data_exists?(reg_child + '\Atraxi', {:name=>"OC", :type=>:string, :data=>"Data"}).should == true + expect(@registry.data_exists?(reg_child + '\Atraxi', {:name=>"OC", :type=>:string, :data=>"Data"})).to eq(true) @registry.architecture = :x86_64 - @registry.key_exists?(reg_child + '\Atraxi').should == false + expect(@registry.key_exists?(reg_child + '\Atraxi')).to eq(false) end end @@ -244,16 +244,16 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.run_action(:create) @report = @resource_reporter.prepare_run_data - @report["action"].should == "end" - @report["resources"][0]["type"].should == "registry_key" - @report["resources"][0]["name"].should == resource_name - @report["resources"][0]["id"].should == reg_child + '\Ood' - @report["resources"][0]["after"][:values].should == [{:name=>"ReportingVal1", :type=>:string, :data=>"report1"}, - {:name=>"ReportingVal2", :type=>:string, :data=>"report2"}] - @report["resources"][0]["before"][:values].should == [] - @report["resources"][0]["result"].should == "create" - @report["status"].should == "success" - @report["total_res_count"].should == "1" + expect(@report["action"]).to eq("end") + expect(@report["resources"][0]["type"]).to eq("registry_key") + expect(@report["resources"][0]["name"]).to eq(resource_name) + expect(@report["resources"][0]["id"]).to eq(reg_child + '\Ood') + expect(@report["resources"][0]["after"][:values]).to eq([{:name=>"ReportingVal1", :type=>:string, :data=>"report1"}, + {:name=>"ReportingVal2", :type=>:string, :data=>"report2"}]) + expect(@report["resources"][0]["before"][:values]).to eq([]) + expect(@report["resources"][0]["result"]).to eq("create") + expect(@report["status"]).to eq("success") + expect(@report["total_res_count"]).to eq("1") end context "while running in whyrun mode" do @@ -266,15 +266,15 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) @new_resource.recursive(false) @new_resource.run_action(:create) # should not raise_error - @registry.key_exists?(reg_child + '\Slitheen').should == false - @registry.key_exists?(reg_child + '\Slitheen\Raxicoricofallapatorius').should == false + expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false) + expect(@registry.key_exists?(reg_child + '\Slitheen\Raxicoricofallapatorius')).to eq(false) end it "does not create key if the action is create" do @new_resource.key(reg_child + '\Slitheen') @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) @new_resource.recursive(false) @new_resource.run_action(:create) - @registry.key_exists?(reg_child + '\Slitheen').should == false + expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false) end end end @@ -289,9 +289,9 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) @new_resource.run_action(:create_if_missing) - @registry.key_exists?(reg_parent).should == true - @registry.key_exists?(reg_child).should == true - @registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"}).should == true + expect(@registry.key_exists?(reg_parent)).to eq(true) + expect(@registry.key_exists?(reg_child)).to eq(true) + expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) end it "does not create the key if it already exists with same value, type and data" do @@ -299,8 +299,8 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) @new_resource.run_action(:create_if_missing) - @registry.key_exists?(reg_child).should == true - @registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"}).should == true + expect(@registry.key_exists?(reg_child)).to eq(true) + expect(@registry.data_exists?(reg_child, {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) end it "creates a value if it does not exist" do @@ -308,7 +308,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"Mango", :type=>:string, :data=>"Yellow"}]) @new_resource.run_action(:create_if_missing) - @registry.data_exists?(reg_child, {:name=>"Mango", :type=>:string, :data=>"Yellow"}).should == true + expect(@registry.data_exists?(reg_child, {:name=>"Mango", :type=>:string, :data=>"Yellow"})).to eq(true) end it "creates subkey if parent exists" do @@ -317,15 +317,15 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(false) @new_resource.run_action(:create_if_missing) - @registry.key_exists?(reg_child + '\Pyrovile').should == true - @registry.value_exists?(reg_child + '\Pyrovile', {:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]}).should == true + expect(@registry.key_exists?(reg_child + '\Pyrovile')).to eq(true) + expect(@registry.value_exists?(reg_child + '\Pyrovile', {:name=>"Chef", :type=>:multi_string, :data=>["OpscodeOrange", "Rules"]})).to eq(true) end it "gives error if action create and parent does not exist and recursive is set to false" do @new_resource.key(reg_child + '\Sontaran\Sontar') @new_resource.values([{:name=>"OC", :type=>:string, :data=>"MissingData"}]) @new_resource.recursive(false) - lambda{@new_resource.run_action(:create_if_missing)}.should raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect{@new_resource.run_action(:create_if_missing)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "creates missing keys if action create and parent does not exist and recursive is set to true" do @@ -334,8 +334,8 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(true) @new_resource.run_action(:create_if_missing) - @registry.key_exists?(reg_child + '\Sontaran\Sontar').should == true - @registry.value_exists?(reg_child + '\Sontaran\Sontar', {:name=>"OC", :type=>:string, :data=>"MissingData"}).should == true + expect(@registry.key_exists?(reg_child + '\Sontaran\Sontar')).to eq(true) + expect(@registry.value_exists?(reg_child + '\Sontaran\Sontar', {:name=>"OC", :type=>:string, :data=>"MissingData"})).to eq(true) end it "creates key with multiple value as specified" do @@ -345,7 +345,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.run_action(:create_if_missing) @new_resource.values.each do |value| - @registry.value_exists?(reg_child + '\Adipose', value).should == true + expect(@registry.value_exists?(reg_child + '\Adipose', value)).to eq(true) end end @@ -356,15 +356,15 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.run_action(:create_if_missing) @report = @resource_reporter.prepare_run_data - @report["action"].should == "end" - @report["resources"][0]["type"].should == "registry_key" - @report["resources"][0]["name"].should == resource_name - @report["resources"][0]["id"].should == reg_child + '\Judoon' - @report["resources"][0]["after"][:values].should == [{:name=>"ReportingVal3", :type=>:string, :data=>"report3"}] - @report["resources"][0]["before"][:values].should == [] - @report["resources"][0]["result"].should == "create_if_missing" - @report["status"].should == "success" - @report["total_res_count"].should == "1" + expect(@report["action"]).to eq("end") + expect(@report["resources"][0]["type"]).to eq("registry_key") + expect(@report["resources"][0]["name"]).to eq(resource_name) + expect(@report["resources"][0]["id"]).to eq(reg_child + '\Judoon') + expect(@report["resources"][0]["after"][:values]).to eq([{:name=>"ReportingVal3", :type=>:string, :data=>"report3"}]) + expect(@report["resources"][0]["before"][:values]).to eq([]) + expect(@report["resources"][0]["result"]).to eq("create_if_missing") + expect(@report["status"]).to eq("success") + expect(@report["total_res_count"]).to eq("1") end context "while running in whyrun mode" do @@ -377,15 +377,15 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) @new_resource.recursive(false) @new_resource.run_action(:create_if_missing) # should not raise_error - @registry.key_exists?(reg_child + '\Zygons').should == false - @registry.key_exists?(reg_child + '\Zygons\Zygor').should == false + expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false) + expect(@registry.key_exists?(reg_child + '\Zygons\Zygor')).to eq(false) end it "does nothing if the action is create_if_missing" do @new_resource.key(reg_child + '\Zygons') @new_resource.values([{:name=>"BriskWalk",:type=>:string,:data=>"is good for health"}]) @new_resource.recursive(false) @new_resource.run_action(:create_if_missing) - @registry.key_exists?(reg_child + '\Zygons').should == false + expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false) end end end @@ -397,24 +397,24 @@ describe Chef::Resource::RegistryKey, :windows_only do end it "takes no action if the specified key path does not exist in the system" do - @registry.key_exists?(reg_parent + '\Osirian').should == false + expect(@registry.key_exists?(reg_parent + '\Osirian')).to eq(false) @new_resource.key(reg_parent+ '\Osirian') @new_resource.recursive(false) @new_resource.run_action(:delete) - @registry.key_exists?(reg_parent + '\Osirian').should == false + expect(@registry.key_exists?(reg_parent + '\Osirian')).to eq(false) end it "takes no action if the key exists but the value does not" do - @registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"}).should == true + expect(@registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) @new_resource.key(reg_parent + '\Opscode') @new_resource.values([{:name=>"LooksLike", :type=>:multi_string, :data=>["SeattleGrey", "OCOrange"]}]) @new_resource.recursive(false) @new_resource.run_action(:delete) - @registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"}).should == true + expect(@registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) end it "deletes only specified values under a key path" do @@ -423,9 +423,9 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(false) @new_resource.run_action(:delete) - @registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"}).should == true - @registry.value_exists?(reg_parent + '\Opscode', {:name=>"AKA", :type=>:string, :data=>"OC"}).should == false - @registry.value_exists?(reg_parent + '\Opscode', {:name=>"Opscode", :type=>:multi_string, :data=>["Seattle", "Washington"]}).should == false + expect(@registry.data_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(true) + expect(@registry.value_exists?(reg_parent + '\Opscode', {:name=>"AKA", :type=>:string, :data=>"OC"})).to eq(false) + expect(@registry.value_exists?(reg_parent + '\Opscode', {:name=>"Opscode", :type=>:multi_string, :data=>["Seattle", "Washington"]})).to eq(false) end it "it deletes the values with the same name irrespective of it type and data" do @@ -434,7 +434,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(false) @new_resource.run_action(:delete) - @registry.value_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"}).should == false + expect(@registry.value_exists?(reg_parent + '\Opscode', {:name=>"Color", :type=>:string, :data=>"Orange"})).to eq(false) end it "prepares the reporting data for action :delete" do @@ -445,19 +445,19 @@ describe Chef::Resource::RegistryKey, :windows_only do @report = @resource_reporter.prepare_run_data - @registry.value_exists?(reg_parent + '\ReportKey', [{:name=>"ReportVal4", :type=>:string, :data=>"report4"},{:name=>"ReportVal5", :type=>:string, :data=>"report5"}]).should == false + expect(@registry.value_exists?(reg_parent + '\ReportKey', [{:name=>"ReportVal4", :type=>:string, :data=>"report4"},{:name=>"ReportVal5", :type=>:string, :data=>"report5"}])).to eq(false) - @report["action"].should == "end" - @report["resources"].count.should == 1 - @report["resources"][0]["type"].should == "registry_key" - @report["resources"][0]["name"].should == resource_name - @report["resources"][0]["id"].should == reg_parent + '\ReportKey' - @report["resources"][0]["before"][:values].should == [{:name=>"ReportVal4", :type=>:string, :data=>"report4"}, - {:name=>"ReportVal5", :type=>:string, :data=>"report5"}] + expect(@report["action"]).to eq("end") + expect(@report["resources"].count).to eq(1) + expect(@report["resources"][0]["type"]).to eq("registry_key") + expect(@report["resources"][0]["name"]).to eq(resource_name) + expect(@report["resources"][0]["id"]).to eq(reg_parent + '\ReportKey') + expect(@report["resources"][0]["before"][:values]).to eq([{:name=>"ReportVal4", :type=>:string, :data=>"report4"}, + {:name=>"ReportVal5", :type=>:string, :data=>"report5"}]) #Not testing for after values to match since after -> new_resource values. - @report["resources"][0]["result"].should == "delete" - @report["status"].should == "success" - @report["total_res_count"].should == "1" + expect(@report["resources"][0]["result"]).to eq("delete") + expect(@report["status"]).to eq("success") + expect(@report["total_res_count"]).to eq("1") end context "while running in whyrun mode" do @@ -470,7 +470,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(false) @new_resource.run_action(:delete) - @registry.key_exists?(reg_parent + '\OpscodeWhyRun').should == true + expect(@registry.key_exists?(reg_parent + '\OpscodeWhyRun')).to eq(true) end end end @@ -482,13 +482,13 @@ describe Chef::Resource::RegistryKey, :windows_only do end it "takes no action if the specified key path does not exist in the system" do - @registry.key_exists?(reg_parent + '\Osirian').should == false + expect(@registry.key_exists?(reg_parent + '\Osirian')).to eq(false) @new_resource.key(reg_parent + '\Osirian') @new_resource.recursive(false) @new_resource.run_action(:delete_key) - @registry.key_exists?(reg_parent + '\Osirian').should == false + expect(@registry.key_exists?(reg_parent + '\Osirian')).to eq(false) end it "deletes key if it has no subkeys and recursive == false" do @@ -496,13 +496,13 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(false) @new_resource.run_action(:delete_key) - @registry.key_exists?(reg_parent + '\OpscodeTest').should == false + expect(@registry.key_exists?(reg_parent + '\OpscodeTest')).to eq(false) end it "raises an exception if the key has subkeys and recursive == false" do @new_resource.key(reg_parent) @new_resource.recursive(false) - lambda{@new_resource.run_action(:delete_key)}.should raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect{@new_resource.run_action(:delete_key)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "ignores the values under a key" do @@ -517,7 +517,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(true) @new_resource.run_action(:delete_key) - @registry.key_exists?(reg_parent + '\Opscode').should == false + expect(@registry.key_exists?(reg_parent + '\Opscode')).to eq(false) end it "prepares the reporting data for action :delete_key" do @@ -526,16 +526,16 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.run_action(:delete_key) @report = @resource_reporter.prepare_run_data - @report["action"].should == "end" - @report["resources"][0]["type"].should == "registry_key" - @report["resources"][0]["name"].should == resource_name - @report["resources"][0]["id"].should == reg_parent + '\ReportKey' + expect(@report["action"]).to eq("end") + expect(@report["resources"][0]["type"]).to eq("registry_key") + expect(@report["resources"][0]["name"]).to eq(resource_name) + expect(@report["resources"][0]["id"]).to eq(reg_parent + '\ReportKey') #Not testing for before or after values to match since #after -> new_resource.values and #before -> current_resource.values - @report["resources"][0]["result"].should == "delete_key" - @report["status"].should == "success" - @report["total_res_count"].should == "1" + expect(@report["resources"][0]["result"]).to eq("delete_key") + expect(@report["status"]).to eq("success") + expect(@report["total_res_count"]).to eq("1") end context "while running in whyrun mode" do before (:each) do @@ -554,7 +554,7 @@ describe Chef::Resource::RegistryKey, :windows_only do @new_resource.recursive(false) @new_resource.run_action(:delete_key) - @registry.key_exists?(reg_parent + '\OpscodeWhyRun').should == true + expect(@registry.key_exists?(reg_parent + '\OpscodeWhyRun')).to eq(true) end end end diff --git a/spec/functional/resource/remote_directory_spec.rb b/spec/functional/resource/remote_directory_spec.rb index f9eb20711e..bcafca7399 100644 --- a/spec/functional/resource/remote_directory_spec.rb +++ b/spec/functional/resource/remote_directory_spec.rb @@ -81,12 +81,12 @@ describe Chef::Resource::RemoteDirectory do it "transfers the directory with all contents" do expected_files.each do |file_path| - File.should exist(file_path) + expect(File).to exist(file_path) end end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end @@ -98,13 +98,13 @@ describe Chef::Resource::RemoteDirectory do it "does not modify the expected state of the directory" do expected_files.each do |file_path| - File.should exist(file_path) + expect(File).to exist(file_path) end end it "does not remove unmanaged files" do - File.should exist(@existing1) - File.should exist(@existing2) + expect(File).to exist(@existing1) + expect(File).to exist(@existing2) end end @@ -116,12 +116,12 @@ describe Chef::Resource::RemoteDirectory do it "does not modify the expected state of the directory" do expected_files.each do |file_path| - File.should exist(file_path) + expect(File).to exist(file_path) end end it "is not marked as updated by last action" do - resource_second_pass.should_not be_updated_by_last_action + expect(resource_second_pass).not_to be_updated_by_last_action end end @@ -142,8 +142,8 @@ describe Chef::Resource::RemoteDirectory do modified_subdir_file_checksum = sha256_checksum(modified_subdir_file) resource.run_action(:create) - sha256_checksum(modified_file).should == modified_file_checksum - sha256_checksum(modified_subdir_file).should == modified_subdir_file_checksum + expect(sha256_checksum(modified_file)).to eq(modified_file_checksum) + expect(sha256_checksum(modified_subdir_file)).to eq(modified_subdir_file_checksum) end end end @@ -160,7 +160,7 @@ describe Chef::Resource::RemoteDirectory do it "creates the directory contents as normal" do expected_files.each do |file_path| - File.should exist(file_path) + expect(File).to exist(file_path) end end @@ -173,18 +173,18 @@ describe Chef::Resource::RemoteDirectory do end it "removes unmanaged files" do - File.should_not exist(@existing1) - File.should_not exist(@existing2) + expect(File).not_to exist(@existing1) + expect(File).not_to exist(@existing2) end it "does not modify managed files" do expected_files.each do |file_path| - File.should exist(file_path) + expect(File).to exist(file_path) end end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end @@ -204,14 +204,14 @@ describe Chef::Resource::RemoteDirectory do end it "removes files in subdirectories before files above" do - File.should_not exist(@existing1) - File.should_not exist(@existing2) - File.should_not exist(@existing3) - File.should_not exist(@existing4) + expect(File).not_to exist(@existing1) + expect(File).not_to exist(@existing2) + expect(File).not_to exist(@existing3) + expect(File).not_to exist(@existing4) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end diff --git a/spec/functional/resource/remote_file_spec.rb b/spec/functional/resource/remote_file_spec.rb index ccdf1cb812..29091fd785 100644 --- a/spec/functional/resource/remote_file_spec.rb +++ b/spec/functional/resource/remote_file_spec.rb @@ -137,20 +137,20 @@ describe Chef::Resource::RemoteFile do let(:source) { 'http://localhost:9000/nyan_cat_content_length_compressed.png' } before do - File.should_not exist(path) + expect(File).not_to exist(path) resource.run_action(:create) end it "should create the file" do - File.should exist(path) + expect(File).to exist(path) end it "should mark the resource as updated" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end it "has the correct content" do - binread(path).should == expected_content + expect(binread(path)).to eq(expected_content) end end @@ -159,20 +159,20 @@ describe Chef::Resource::RemoteFile do let(:source) { 'http://localhost:9000/nyan_cat_content_length.png' } before do - File.should_not exist(path) + expect(File).not_to exist(path) resource.run_action(:create) end it "should create the file" do - File.should exist(path) + expect(File).to exist(path) end it "should mark the resource as updated" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end it "has the correct content" do - binread(path).should == expected_content + expect(binread(path)).to eq(expected_content) end end @@ -180,11 +180,11 @@ describe Chef::Resource::RemoteFile do let(:source) { 'http://localhost:9000/nyan_cat_truncated_compressed.png' } before do - File.should_not exist(path) + expect(File).not_to exist(path) end it "should raise ContentLengthMismatch" do - lambda { resource.run_action(:create) }.should raise_error(Chef::Exceptions::ContentLengthMismatch) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::ContentLengthMismatch) #File.should_not exist(path) # XXX: CHEF-5081 end end @@ -193,11 +193,11 @@ describe Chef::Resource::RemoteFile do let(:source) { 'http://localhost:9000/nyan_cat_truncated.png' } before do - File.should_not exist(path) + expect(File).not_to exist(path) end it "should raise ContentLengthMismatch" do - lambda { resource.run_action(:create) }.should raise_error(Chef::Exceptions::ContentLengthMismatch) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::ContentLengthMismatch) #File.should_not exist(path) # XXX: CHEF-5081 end end @@ -207,20 +207,20 @@ describe Chef::Resource::RemoteFile do let(:source) { 'http://localhost:9000/nyan_cat_transfer_encoding.png' } before do - File.should_not exist(path) + expect(File).not_to exist(path) resource.run_action(:create) end it "should create the file" do - File.should exist(path) + expect(File).to exist(path) end it "should mark the resource as updated" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end it "has the correct content" do - binread(path).should == expected_content + expect(binread(path)).to eq(expected_content) end end @@ -228,12 +228,12 @@ describe Chef::Resource::RemoteFile do let(:source) { 'http://localhost:0000/seattle_capo.png' } before do - File.should_not exist(path) + expect(File).not_to exist(path) end it "should not create the file" do expect{ resource.run_action(:create) }.to raise_error - File.should_not exist(path) + expect(File).not_to exist(path) end end end diff --git a/spec/functional/resource/template_spec.rb b/spec/functional/resource/template_spec.rb index fefd995743..d7b35e7450 100644 --- a/spec/functional/resource/template_spec.rb +++ b/spec/functional/resource/template_spec.rb @@ -69,7 +69,7 @@ describe Chef::Resource::Template do resource.source('openldap_variable_stuff.conf.erb') resource.variables(:secret => "nutella") resource.run_action(:create) - IO.read(path).should == "super secret is nutella" + expect(IO.read(path)).to eq("super secret is nutella") end it "creates the template with the rendered content using a local erb file when the :create action is run" do @@ -77,7 +77,7 @@ describe Chef::Resource::Template do resource.cookbook(nil) resource.local(true) resource.run_action(:create) - IO.read(path).should == expected_content + expect(IO.read(path)).to eq(expected_content) end end @@ -96,7 +96,7 @@ describe Chef::Resource::Template do shared_examples "a template with helpers" do it "generates expected content by calling helper methods" do resource.run_action(:create) - binread(path).strip.should == expected_content + expect(binread(path).strip).to eq(expected_content) end end @@ -202,7 +202,7 @@ describe Chef::Resource::Template do it "output should contain platform's line endings" do resource.run_action(:create) binread(path).each_line do |line| - line.should end_with(Chef::Platform.windows? ? "\r\n" : "\n") + expect(line).to end_with(Chef::Platform.windows? ? "\r\n" : "\n") end end end diff --git a/spec/functional/resource/user/dscl_spec.rb b/spec/functional/resource/user/dscl_spec.rb index ba508e3258..45b6754453 100644 --- a/spec/functional/resource/user/dscl_spec.rb +++ b/spec/functional/resource/user/dscl_spec.rb @@ -37,15 +37,15 @@ describe "Chef::Resource::User with Chef::Provider::User::Dscl provider", metada end def user_should_exist - shell_out("/usr/bin/dscl . -ls /Users").stdout.should include username + expect(shell_out("/usr/bin/dscl . -ls /Users").stdout).to include username end def check_password(pass) # In order to test the password we use dscl passwd command since # that's the only command that gets the user password from CLI. - shell_out("dscl . -passwd /Users/greatchef #{pass} new_password").exitstatus.should == 0 + expect(shell_out("dscl . -passwd /Users/greatchef #{pass} new_password").exitstatus).to eq(0) # Now reset the password back - shell_out("dscl . -passwd /Users/greatchef new_password #{pass}").exitstatus.should == 0 + expect(shell_out("dscl . -passwd /Users/greatchef new_password #{pass}").exitstatus).to eq(0) end let(:node) do @@ -191,7 +191,7 @@ c5adbbac718b7eb99463a7b679571e0f\ user_resource.run_action(:remove) groups.each do |group| # Do not raise an error when group is empty - shell_out("dscl . read /Groups/staff GroupMembership").stdout.should_not include(group) + expect(shell_out("dscl . read /Groups/staff GroupMembership").stdout).not_to include(group) end end end diff --git a/spec/functional/resource/user/useradd_spec.rb b/spec/functional/resource/user/useradd_spec.rb index 1fbe6fcb4d..6b962c19aa 100644 --- a/spec/functional/resource/user/useradd_spec.rb +++ b/spec/functional/resource/user/useradd_spec.rb @@ -70,9 +70,9 @@ describe Chef::Provider::User::Useradd, metadata do def password_should_be_set if ohai[:platform] == "aix" - pw_entry.passwd.should == "!" + expect(pw_entry.passwd).to eq("!") else - pw_entry.passwd.should == "x" + expect(pw_entry.passwd).to eq("x") end end @@ -145,12 +145,12 @@ describe Chef::Provider::User::Useradd, metadata do pending(reason) end user_resource.run_action(:create) - user_resource.should be_updated_by_last_action + expect(user_resource).to be_updated_by_last_action end it "ensures the user exists" do - pw_entry.name.should == username + expect(pw_entry.name).to eq(username) end # On Debian, the only constraints are that usernames must neither start @@ -171,7 +171,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:username) { "t'bilisi" } it "ensures the user exists" do - pw_entry.name.should == username + expect(pw_entry.name).to eq(username) end end @@ -181,7 +181,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:uid) { 1999 } it "ensures the user has the given uid" do - pw_entry.uid.should == "1999" + expect(pw_entry.uid).to eq("1999") end end @@ -189,14 +189,14 @@ describe Chef::Provider::User::Useradd, metadata do let(:comment) { "hello this is dog" } it "ensures the comment is set" do - pw_entry.gecos.should == "hello this is dog" + expect(pw_entry.gecos).to eq("hello this is dog") end context "in standard gecos format" do let(:comment) { "Bobo T. Clown,some building,555-555-5555,@boboclown" } it "ensures the comment is set" do - pw_entry.gecos.should == comment + expect(pw_entry.gecos).to eq(comment) end end @@ -206,7 +206,7 @@ describe Chef::Provider::User::Useradd, metadata do it "ensures the comment is set" do actual = pw_entry.gecos actual.force_encoding(Encoding::UTF_8) if "".respond_to?(:force_encoding) - actual.should == comment + expect(actual).to eq(comment) end end @@ -214,7 +214,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:comment) { "don't go" } it "ensures the comment is set" do - pw_entry.gecos.should == comment + expect(pw_entry.gecos).to eq(comment) end end end @@ -223,17 +223,17 @@ describe Chef::Provider::User::Useradd, metadata do let(:home) { "/home/#{username}" } it "ensures the user's home is set to the given path" do - pw_entry.home.should == "/home/#{username}" + expect(pw_entry.home).to eq("/home/#{username}") end if %w{rhel fedora}.include?(OHAI_SYSTEM["platform_family"]) # Inconsistent behavior. See: CHEF-2205 it "creates the home dir when not explicitly asked to on RHEL (XXX)" do - File.should exist("/home/#{username}") + expect(File).to exist("/home/#{username}") end else it "does not create the home dir without `manage_home'" do - File.should_not exist("/home/#{username}") + expect(File).not_to exist("/home/#{username}") end end @@ -241,7 +241,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:manage_home) { true } it "ensures the user's home directory exists" do - File.should exist("/home/#{username}") + expect(File).to exist("/home/#{username}") end end end @@ -259,7 +259,7 @@ describe Chef::Provider::User::Useradd, metadata do it "sets the user's shadow password" do password_should_be_set - etc_shadow.should include(expected_shadow) + expect(etc_shadow).to include(expected_shadow) end end @@ -284,7 +284,7 @@ describe Chef::Provider::User::Useradd, metadata do end it "ensures the user has the properties of a system user" do - pw_entry.uid.to_i.should be < uid_min.to_i + expect(pw_entry.uid.to_i).to be < uid_min.to_i end end end # when the user does not exist beforehand @@ -318,9 +318,9 @@ describe Chef::Provider::User::Useradd, metadata do pending(reason) end existing_user.run_action(:create) - existing_user.should be_updated_by_last_action + expect(existing_user).to be_updated_by_last_action user_resource.run_action(:create) - user_resource.updated_by_last_action?.should == expect_updated? + expect(user_resource.updated_by_last_action?).to eq(expect_updated?) end context "and all properties are in the desired state" do @@ -350,7 +350,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:expect_updated?) { false } it "does not update the user" do - user_resource.should_not be_updated + expect(user_resource).not_to be_updated end end @@ -359,7 +359,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:existing_uid) { 1998 } it "ensures the uid is set to the desired value" do - pw_entry.uid.should == "1999" + expect(pw_entry.uid).to eq("1999") end end @@ -368,7 +368,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:existing_comment) { "woof" } it "ensures the comment field is set to the desired value" do - pw_entry.gecos.should == "hello this is dog" + expect(pw_entry.gecos).to eq("hello this is dog") end end @@ -376,15 +376,15 @@ describe Chef::Provider::User::Useradd, metadata do let(:existing_home) { "/home/foo" } let(:home) { "/home/bar" } it "ensures the home directory is set to the desired value" do - pw_entry.home.should == "/home/bar" + expect(pw_entry.home).to eq("/home/bar") end context "and manage_home is enabled" do let(:existing_manage_home) { true } let(:manage_home) { true } it "moves the home directory to the new location" do - File.should_not exist("/home/foo") - File.should exist("/home/bar") + expect(File).not_to exist("/home/foo") + expect(File).to exist("/home/bar") end end @@ -396,19 +396,19 @@ describe Chef::Provider::User::Useradd, metadata do # Inconsistent behavior. See: CHEF-2205 it "created the home dir b/c of CHEF-2205 so it still exists" do # This behavior seems contrary to expectation and non-convergent. - File.should_not exist("/home/foo") - File.should exist("/home/bar") + expect(File).not_to exist("/home/foo") + expect(File).to exist("/home/bar") end elsif ohai[:platform] == "aix" it "creates the home dir in the desired location" do - File.should_not exist("/home/foo") - File.should exist("/home/bar") + expect(File).not_to exist("/home/foo") + expect(File).to exist("/home/bar") end else it "does not create the home dir in the desired location (XXX)" do # This behavior seems contrary to expectation and non-convergent. - File.should_not exist("/home/foo") - File.should_not exist("/home/bar") + expect(File).not_to exist("/home/foo") + expect(File).not_to exist("/home/bar") end end end @@ -419,8 +419,8 @@ describe Chef::Provider::User::Useradd, metadata do it "leaves the old home directory around (XXX)" do # Would it be better to remove the old home? - File.should exist("/home/foo") - File.should_not exist("/home/bar") + expect(File).to exist("/home/foo") + expect(File).not_to exist("/home/bar") end end end @@ -439,7 +439,7 @@ describe Chef::Provider::User::Useradd, metadata do it "ensures the password is set" do password_should_be_set - etc_shadow.should include(expected_shadow) + expect(etc_shadow).to include(expected_shadow) end end @@ -468,7 +468,7 @@ describe Chef::Provider::User::Useradd, metadata do it "ensures the password is set to the desired value" do password_should_be_set - etc_shadow.should include(expected_shadow) + expect(etc_shadow).to include(expected_shadow) end end @@ -514,18 +514,18 @@ describe Chef::Provider::User::Useradd, metadata do def user_account_should_be_locked case ohai[:platform] when "aix" - aix_user_lock_status.should == "true" + expect(aix_user_lock_status).to eq("true") else - shadow_password.should include("!") + expect(shadow_password).to include("!") end end def user_account_should_be_unlocked case ohai[:platform] when "aix" - aix_user_lock_status.should == "false" + expect(aix_user_lock_status).to eq("false") else - shadow_password.should_not include("!") + expect(shadow_password).not_to include("!") end end @@ -596,7 +596,7 @@ describe Chef::Provider::User::Useradd, metadata do let(:user_locked_context?) { true } it "does not update the user" do - user_resource.should_not be_updated_by_last_action + expect(user_resource).not_to be_updated_by_last_action end end end @@ -628,8 +628,8 @@ describe Chef::Provider::User::Useradd, metadata do if %w[suse opensuse].include?(OHAI_SYSTEM["platform_family"]) # suse gets this right: it "errors out trying to unlock the user" do - @error.should be_a(Mixlib::ShellOut::ShellCommandFailed) - @error.message.should include("Cannot unlock the password") + expect(@error).to be_a(Mixlib::ShellOut::ShellCommandFailed) + expect(@error.message).to include("Cannot unlock the password") end else @@ -644,13 +644,13 @@ describe Chef::Provider::User::Useradd, metadata do # You should set a password with usermod -p to unlock this user's password. # DEBUG: ---- End output of usermod -U chef-functional-test ---- # DEBUG: Ran usermod -U chef-functional-test returned 0 - @error.should be_nil + expect(@error).to be_nil if ohai[:platform] == "aix" - pw_entry.passwd.should == '*' + expect(pw_entry.passwd).to eq('*') user_account_should_be_unlocked else - pw_entry.passwd.should == 'x' - shadow_password.should include("!") + expect(pw_entry.passwd).to eq('x') + expect(shadow_password).to include("!") end end end @@ -668,7 +668,7 @@ describe Chef::Provider::User::Useradd, metadata do context "and the user is not locked" do it "does not update the user" do - user_resource.should_not be_updated_by_last_action + expect(user_resource).not_to be_updated_by_last_action end end diff --git a/spec/functional/run_lock_spec.rb b/spec/functional/run_lock_spec.rb index 9eec0dab04..0cb8635256 100644 --- a/spec/functional/run_lock_spec.rb +++ b/spec/functional/run_lock_spec.rb @@ -163,13 +163,13 @@ describe Chef::RunLock do let!(:run_lock) { Chef::RunLock.new(lockfile) } it "creates the full path to the lockfile" do - lambda { run_lock.acquire }.should_not raise_error - File.should exist(lockfile) + expect { run_lock.acquire }.not_to raise_error + expect(File).to exist(lockfile) end it "sets FD_CLOEXEC on the lockfile", :supports_cloexec => true do run_lock.acquire - (run_lock.runlock.fcntl(Fcntl::F_GETFD, 0) & Fcntl::FD_CLOEXEC).should == Fcntl::FD_CLOEXEC + expect(run_lock.runlock.fcntl(Fcntl::F_GETFD, 0) & Fcntl::FD_CLOEXEC).to eq(Fcntl::FD_CLOEXEC) end it "allows only one chef client run per lockfile" do @@ -208,7 +208,7 @@ p1 has lock p1 releasing lock p2 has lock E - results.should == expected + expect(results).to eq(expected) end it "clears the lock if the process dies unexpectedly" do @@ -233,12 +233,12 @@ E Process.waitpid2(p2) - results.should =~ /p2 has lock\Z/ + expect(results).to match(/p2 has lock\Z/) end it "test returns true and acquires the lock" do p1 = fork do - run_lock.test.should == true + expect(run_lock.test).to eq(true) sleep 2 exit! 1 end @@ -246,7 +246,7 @@ E wait_on_lock p2 = fork do - run_lock.test.should == false + expect(run_lock.test).to eq(false) exit! 0 end @@ -263,7 +263,7 @@ E wait_on_lock - run_lock.test.should == false + expect(run_lock.test).to eq(false) Process.waitpid2(p1) end @@ -277,7 +277,7 @@ E wait_on_lock sleep 0.5 # Possible race condition on Solaris which pid is observed as 0 - File.read(lockfile).should == p1.to_s + expect(File.read(lockfile)).to eq(p1.to_s) Process.waitpid2(p1) end diff --git a/spec/functional/shell_spec.rb b/spec/functional/shell_spec.rb index f2ce3f53e4..fa9de77b0e 100644 --- a/spec/functional/shell_spec.rb +++ b/spec/functional/shell_spec.rb @@ -105,7 +105,7 @@ describe Shell do it "boots correctly with -lauto" do output, exitstatus = run_chef_shell_with("-lauto") - output.should include("done") + expect(output).to include("done") expect(exitstatus).to eq(0) end @@ -115,7 +115,7 @@ describe Shell do keyboard.puts(show_log_level_code) read_until(out, show_log_level_code) end - output.should include("===fatal===") + expect(output).to include("===fatal===") expect(exitstatus).to eq(0) end @@ -125,7 +125,7 @@ describe Shell do keyboard.puts(show_recipes_code) read_until(out, show_recipes_code) end - output.should include(%q{["override::foo", "override::bar"]}) + expect(output).to include(%q{["override::foo", "override::bar"]}) expect(exitstatus).to eq(0) end end diff --git a/spec/functional/tiny_server_spec.rb b/spec/functional/tiny_server_spec.rb index bfa6ff1ddb..87be948a0d 100644 --- a/spec/functional/tiny_server_spec.rb +++ b/spec/functional/tiny_server_spec.rb @@ -26,39 +26,39 @@ describe TinyServer::API do end it "is a Singleton" do - lambda {TinyServer::API.new}.should raise_error + expect {TinyServer::API.new}.to raise_error end it "clears the router" do @api.get('/blargh', 200, "blargh") @api.clear - @api.routes["GET"].should be_empty + expect(@api.routes["GET"]).to be_empty end it "creates a route for a GET request" do @api.get('/foo/bar', 200, 'hello foobar') # WEBrick gives you the full URI with host, Thin only gave the part after scheme+host+port response = @api.call("REQUEST_METHOD" => "GET", "REQUEST_URI" => 'http://localhost:1974/foo/bar') - response.should == [200, {'Content-Type' => 'application/json'}, [ 'hello foobar' ]] + expect(response).to eq([200, {'Content-Type' => 'application/json'}, [ 'hello foobar' ]]) end it "creates a route for a request with a block" do block_called = false @api.get('/bar/baz', 200) { block_called = true; 'hello barbaz' } response = @api.call("REQUEST_METHOD" => "GET", "REQUEST_URI" => 'http://localhost:1974/bar/baz') - response.should == [200, {'Content-Type' => 'application/json'}, [ 'hello barbaz' ]] - block_called.should be_true + expect(response).to eq([200, {'Content-Type' => 'application/json'}, [ 'hello barbaz' ]]) + expect(block_called).to be_truthy end it "returns debugging info for 404s" do response = @api.call("REQUEST_METHOD" => "GET", "REQUEST_URI" => '/no_such_thing') - response[0].should == 404 - response[1].should == {'Content-Type' => 'application/json'} - response[2].should be_a_kind_of(Array) + expect(response[0]).to eq(404) + expect(response[1]).to eq({'Content-Type' => 'application/json'}) + expect(response[2]).to be_a_kind_of(Array) response_obj = Chef::JSONCompat.from_json(response[2].first) - response_obj["message"].should == "no data matches the request for /no_such_thing" - response_obj["available_routes"].should == {"GET"=>[], "PUT"=>[], "POST"=>[], "DELETE"=>[]} - response_obj["request"].should == {"REQUEST_METHOD"=>"GET", "REQUEST_URI"=>"/no_such_thing"} + expect(response_obj["message"]).to eq("no data matches the request for /no_such_thing") + expect(response_obj["available_routes"]).to eq({"GET"=>[], "PUT"=>[], "POST"=>[], "DELETE"=>[]}) + expect(response_obj["request"]).to eq({"REQUEST_METHOD"=>"GET", "REQUEST_URI"=>"/no_such_thing"}) end end @@ -71,7 +71,7 @@ describe TinyServer::Manager do TinyServer::API.instance.get("/index", 200, "[\"hello\"]") rest = Chef::REST.new('http://localhost:9000', false, false) - rest.get_rest("index").should == ["hello"] + expect(rest.get_rest("index")).to eq(["hello"]) @server.stop end diff --git a/spec/functional/util/path_helper_spec.rb b/spec/functional/util/path_helper_spec.rb index ccdf383c22..0321702bb8 100644 --- a/spec/functional/util/path_helper_spec.rb +++ b/spec/functional/util/path_helper_spec.rb @@ -31,7 +31,7 @@ describe Chef::Util::PathHelper, "escape_glob" do end pattern = File.join(PathHelper.escape_glob(dir), "*") - Dir.glob(pattern).map { |x| File.basename(x) }.should match_array(files) + expect(Dir.glob(pattern).map { |x| File.basename(x) }).to match_array(files) end end end diff --git a/spec/functional/version_spec.rb b/spec/functional/version_spec.rb index a342206161..71ba4d5b2f 100644 --- a/spec/functional/version_spec.rb +++ b/spec/functional/version_spec.rb @@ -28,7 +28,7 @@ describe "Chef Versions" do binaries.each do |binary| it "#{binary} version should be sane" do - shell_out!("ruby #{File.join("bin", binary)} -v", :cwd => chef_dir).stdout.chomp.should == "Chef: #{Chef::VERSION}" + expect(shell_out!("ruby #{File.join("bin", binary)} -v", :cwd => chef_dir).stdout.chomp).to eq("Chef: #{Chef::VERSION}") end end diff --git a/spec/functional/win32/registry_helper_spec.rb b/spec/functional/win32/registry_helper_spec.rb index 830d6f4777..7b070e6fe1 100644 --- a/spec/functional/win32/registry_helper_spec.rb +++ b/spec/functional/win32/registry_helper_spec.rb @@ -34,7 +34,7 @@ describe Chef::Resource::RegistryKey, :unix_only do it "throws an exception because you don't have a windows registry (derp)" do @resource.key("HKCU\\Software\\Opscode") @resource.values([{:name=>"Color", :type=>:string, :data=>"Orange"}]) - lambda{@resource.run_action(:create)}.should raise_error(Chef::Exceptions::Win32NotWindows) + expect{@resource.run_action(:create)}.to raise_error(Chef::Exceptions::Win32NotWindows) end end end @@ -84,197 +84,197 @@ describe 'Chef::Win32::Registry', :windows_only do describe "hive_exists?" do it "returns true if the hive exists" do - @registry.hive_exists?("HKCU\\Software\\Root").should == true + expect(@registry.hive_exists?("HKCU\\Software\\Root")).to eq(true) end it "returns false if the hive does not exist" do - hive = @registry.hive_exists?("LYRU\\Software\\Root").should == false + hive = expect(@registry.hive_exists?("LYRU\\Software\\Root")).to eq(false) end end describe "key_exists?" do it "returns true if the key path exists" do - @registry.key_exists?("HKCU\\Software\\Root\\Branch\\Flower").should == true + expect(@registry.key_exists?("HKCU\\Software\\Root\\Branch\\Flower")).to eq(true) end it "returns false if the key path does not exist" do - @registry.key_exists?("HKCU\\Software\\Branch\\Flower").should == false + expect(@registry.key_exists?("HKCU\\Software\\Branch\\Flower")).to eq(false) end it "throws an exception if the hive does not exist" do - lambda {@registry.key_exists?("JKLM\\Software\\Branch\\Flower")}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.key_exists?("JKLM\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end describe "key_exists!" do it "returns true if the key path exists" do - @registry.key_exists!("HKCU\\Software\\Root\\Branch\\Flower").should == true + expect(@registry.key_exists!("HKCU\\Software\\Root\\Branch\\Flower")).to eq(true) end it "throws an exception if the key path does not exist" do - lambda {@registry.key_exists!("HKCU\\Software\\Branch\\Flower")}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.key_exists!("HKCU\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - lambda {@registry.key_exists!("JKLM\\Software\\Branch\\Flower")}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.key_exists!("JKLM\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end describe "value_exists?" do it "throws an exception if the hive does not exist" do - lambda {@registry.value_exists?("JKLM\\Software\\Branch\\Flower", {:name=>"Petals"})}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.value_exists?("JKLM\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - lambda {@registry.value_exists?("HKCU\\Software\\Branch\\Flower", {:name=>"Petals"})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.value_exists?("HKCU\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the value exists" do - @registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals"}).should == true + expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals"})).to eq(true) end it "returns false if the value does not exist" do - @registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"FOOBAR"}).should == false + expect(@registry.value_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"FOOBAR"})).to eq(false) end end describe "value_exists!" do it "throws an exception if the hive does not exist" do - lambda {@registry.value_exists!("JKLM\\Software\\Branch\\Flower", {:name=>"Petals"})}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.value_exists!("JKLM\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - lambda {@registry.value_exists!("HKCU\\Software\\Branch\\Flower", {:name=>"Petals"})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.value_exists!("HKCU\\Software\\Branch\\Flower", {:name=>"Petals"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the value exists" do - @registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals"}).should == true + expect(@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals"})).to eq(true) end it "throws an exception if the value does not exist" do - lambda {@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"FOOBAR"})}.should raise_error(Chef::Exceptions::Win32RegValueMissing) + expect {@registry.value_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"FOOBAR"})}.to raise_error(Chef::Exceptions::Win32RegValueMissing) end end describe "data_exists?" do it "throws an exception if the hive does not exist" do - lambda {@registry.data_exists?("JKLM\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.data_exists?("JKLM\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - lambda {@registry.data_exists?("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.data_exists?("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if all the data matches" do - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]}).should == true + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(true) end it "returns false if the name does not exist" do - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"slateP", :type=>:multi_string, :data=>["Pink", "Delicate"]}).should == false + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"slateP", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(false) end it "returns false if the types do not match" do - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Pink"}).should == false + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Pink"})).to eq(false) end it "returns false if the data does not match" do - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Mauve", "Delicate"]}).should == false + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Mauve", "Delicate"]})).to eq(false) end end describe "data_exists!" do it "throws an exception if the hive does not exist" do - lambda {@registry.data_exists!("JKLM\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.data_exists!("JKLM\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key does not exist" do - lambda {@registry.data_exists!("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.data_exists!("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if all the data matches" do - @registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]}).should == true + expect(@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Pink", "Delicate"]})).to eq(true) end it "throws an exception if the name does not exist" do - lambda {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"slateP", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.should raise_error(Chef::Exceptions::Win32RegDataMissing) + expect {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"slateP", :type=>:multi_string, :data=>["Pink", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegDataMissing) end it "throws an exception if the types do not match" do - lambda {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Pink"})}.should raise_error(Chef::Exceptions::Win32RegDataMissing) + expect {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Pink"})}.to raise_error(Chef::Exceptions::Win32RegDataMissing) end it "throws an exception if the data does not match" do - lambda {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Mauve", "Delicate"]})}.should raise_error(Chef::Exceptions::Win32RegDataMissing) + expect {@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Mauve", "Delicate"]})}.to raise_error(Chef::Exceptions::Win32RegDataMissing) end end describe "get_values" do it "returns all values for a key if it exists" do values = @registry.get_values("HKCU\\Software\\Root") - values.should be_an_instance_of Array - values.should == [{:name=>"RootType1", :type=>:string, :data=>"fibrous"}, - {:name=>"Roots", :type=>:multi_string, :data=>["strong roots", "healthy tree"]}] + expect(values).to be_an_instance_of Array + expect(values).to eq([{:name=>"RootType1", :type=>:string, :data=>"fibrous"}, + {:name=>"Roots", :type=>:multi_string, :data=>["strong roots", "healthy tree"]}]) end it "throws an exception if the key does not exist" do - lambda {@registry.get_values("HKCU\\Software\\Branch\\Flower")}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.get_values("HKCU\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - lambda {@registry.get_values("JKLM\\Software\\Branch\\Flower")}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.get_values("JKLM\\Software\\Branch\\Flower")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end describe "set_value" do it "updates a value if the key, value exist and type matches and value different" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]}).should == true + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) end it "updates a value if the type does match and the values are different" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Yellow"}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Yellow"}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]}).should == false + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Yellow"})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:string, :data=>"Yellow"})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(false) end it "creates a value if key exists and value does not" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]}).should == true + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) end it "does nothing if data,type and name parameters for the value are same" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]}).should == false - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]}).should == true + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(false) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"Stamen", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})).to eq(true) end it "throws an exception if the key does not exist" do - lambda {@registry.set_value("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.set_value("HKCU\\Software\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - lambda {@registry.set_value("JKLM\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.set_value("JKLM\\Software\\Root\\Branch\\Flower", {:name=>"Petals", :type=>:multi_string, :data=>["Yellow", "Changed Color"]})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end # we are validating that the data gets .to_i called on it when type is a :dword it "casts an integer string given as a dword into an integer" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe32767", :type=>:dword, :data=>"32767"}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe32767", :type=>:dword, :data=>32767}).should == true + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe32767", :type=>:dword, :data=>"32767"})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe32767", :type=>:dword, :data=>32767})).to eq(true) end it "casts a nonsense string given as a dword into zero" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeZero", :type=>:dword, :data=>"whatdoesthisdo"}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeZero", :type=>:dword, :data=>0}).should == true + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeZero", :type=>:dword, :data=>"whatdoesthisdo"})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeZero", :type=>:dword, :data=>0})).to eq(true) end it "throws an exception when trying to cast an array to an int for a dword" do - lambda {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldThrow", :type=>:dword, :data=>["one","two"]})}.should raise_error + expect {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldThrow", :type=>:dword, :data=>["one","two"]})}.to raise_error end # we are validating that the data gets .to_s called on it when type is a :string it "stores the string representation of an array into a string if you pass it an array" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBePainful", :type=>:string, :data=>["one","two"]}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBePainful", :type=>:string, :data=>'["one", "two"]'}).should == true + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBePainful", :type=>:string, :data=>["one","two"]})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBePainful", :type=>:string, :data=>'["one", "two"]'})).to eq(true) end it "stores the string representation of a number into a string if you pass it an number" do - @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe65535", :type=>:string, :data=>65535}).should == true - @registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe65535", :type=>:string, :data=>"65535"}).should == true + expect(@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe65535", :type=>:string, :data=>65535})).to eq(true) + expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBe65535", :type=>:string, :data=>"65535"})).to eq(true) end # we are validating that the data gets .to_a called on it when type is a :multi_string it "throws an exception when a multi-string is passed a number" do - lambda {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldThrow", :type=>:multi_string, :data=>65535})}.should raise_error + expect {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldThrow", :type=>:multi_string, :data=>65535})}.to raise_error end it "throws an exception when a multi-string is passed a string" do - lambda {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeWat", :type=>:multi_string, :data=>"foo"})}.should raise_error + expect {@registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", {:name=>"ShouldBeWat", :type=>:multi_string, :data=>"foo"})}.to raise_error end end @@ -289,22 +289,22 @@ describe 'Chef::Win32::Registry', :windows_only do end it "throws an exception if the path has missing keys but recursive set to false" do - lambda {@registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", false)}.should raise_error(Chef::Exceptions::Win32RegNoRecursive) - @registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker").should == false + expect {@registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", false)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect(@registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker")).to eq(false) end it "creates the key_path if the keys were missing but recursive was set to true" do - @registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", true).should == true - @registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker").should == true + expect(@registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", true)).to eq(true) + expect(@registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker")).to eq(true) end it "does nothing if the key already exists" do - @registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", false).should == true - @registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker").should == true + expect(@registry.create_key("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", false)).to eq(true) + expect(@registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker")).to eq(true) end it "throws an exception of the hive does not exist" do - lambda {@registry.create_key("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", false)}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.create_key("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", false)}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end @@ -317,21 +317,21 @@ describe 'Chef::Win32::Registry', :windows_only do end it "deletes values if the value exists" do - @registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"}).should == true - @registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"}).should == false + expect(@registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(true) + expect(@registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(false) end it "does nothing if value does not exist" do - @registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"}).should == true - @registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"}).should == false + expect(@registry.delete_value("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(true) + expect(@registry.value_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})).to eq(false) end it "throws an exception if the key does not exist?" do - lambda {@registry.delete_value("HKCU\\Software\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.delete_value("HKCU\\Software\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - lambda {@registry.delete_value("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.delete_value("JKLM\\Software\\Root\\Trunk\\Peck\\Woodpecker", {:name=>"Peter", :type=>:string, :data=>"Tiny"})}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end @@ -348,27 +348,27 @@ describe 'Chef::Win32::Registry', :windows_only do end it "deletes a key if it has no subkeys" do - @registry.delete_key("HKCU\\Software\\Root\\Branch\\Fruit", false).should == true - @registry.key_exists?("HKCU\\Software\\Root\\Branch\\Fruit").should == false + expect(@registry.delete_key("HKCU\\Software\\Root\\Branch\\Fruit", false)).to eq(true) + expect(@registry.key_exists?("HKCU\\Software\\Root\\Branch\\Fruit")).to eq(false) end it "throws an exception if key to delete has subkeys and recursive is false" do - lambda { @registry.delete_key("HKCU\\Software\\Root\\Trunk", false) }.should raise_error(Chef::Exceptions::Win32RegNoRecursive) - @registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker").should == true + expect { @registry.delete_key("HKCU\\Software\\Root\\Trunk", false) }.to raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect(@registry.key_exists?("HKCU\\Software\\Root\\Trunk\\Peck\\Woodpecker")).to eq(true) end it "deletes a key if it has subkeys and recursive true" do - @registry.delete_key("HKCU\\Software\\Root\\Trunk", true).should == true - @registry.key_exists?("HKCU\\Software\\Root\\Trunk").should == false + expect(@registry.delete_key("HKCU\\Software\\Root\\Trunk", true)).to eq(true) + expect(@registry.key_exists?("HKCU\\Software\\Root\\Trunk")).to eq(false) end it "does nothing if the key does not exist" do - @registry.delete_key("HKCU\\Software\\Root\\Trunk", true).should == true - @registry.key_exists?("HKCU\\Software\\Root\\Trunk").should == false + expect(@registry.delete_key("HKCU\\Software\\Root\\Trunk", true)).to eq(true) + expect(@registry.key_exists?("HKCU\\Software\\Root\\Trunk")).to eq(false) end it "throws an exception if the hive does not exist" do - lambda {@registry.delete_key("JKLM\\Software\\Root\\Branch\\Flower", false)}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.delete_key("JKLM\\Software\\Root\\Branch\\Flower", false)}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end end @@ -384,29 +384,29 @@ describe 'Chef::Win32::Registry', :windows_only do end it "throws an exception if the hive was missing" do - lambda {@registry.has_subkeys?("LMNO\\Software\\Root")}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.has_subkeys?("LMNO\\Software\\Root")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "throws an exception if the key is missing" do - lambda {@registry.has_subkeys?("HKCU\\Software\\Root\\Trunk\\Red")}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.has_subkeys?("HKCU\\Software\\Root\\Trunk\\Red")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the key has subkeys" do - @registry.has_subkeys?("HKCU\\Software\\Root").should == true + expect(@registry.has_subkeys?("HKCU\\Software\\Root")).to eq(true) end it "returns false if the key has no subkeys" do ::Win32::Registry::HKEY_CURRENT_USER.create "Software\\Root\\Trunk\\Red" - @registry.has_subkeys?("HKCU\\Software\\Root\\Trunk\\Red").should == false + expect(@registry.has_subkeys?("HKCU\\Software\\Root\\Trunk\\Red")).to eq(false) end end describe "get_subkeys" do it "throws an exception if the key is missing" do - lambda {@registry.get_subkeys("HKCU\\Software\\Trunk\\Red")}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.get_subkeys("HKCU\\Software\\Trunk\\Red")}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "throws an exception if the hive does not exist" do - lambda {@registry.get_subkeys("JKLM\\Software\\Root")}.should raise_error(Chef::Exceptions::Win32RegHiveMissing) + expect {@registry.get_subkeys("JKLM\\Software\\Root")}.to raise_error(Chef::Exceptions::Win32RegHiveMissing) end it "returns the array of subkeys for a given key" do subkeys = @registry.get_subkeys("HKCU\\Software\\Root") @@ -414,7 +414,7 @@ describe 'Chef::Win32::Registry', :windows_only do ::Win32::Registry::HKEY_CURRENT_USER.open("Software\\Root", Win32::Registry::KEY_ALL_ACCESS) do |reg| reg.each_key{|name| reg_subkeys << name} end - reg_subkeys.should == subkeys + expect(reg_subkeys).to eq(subkeys) end end @@ -431,37 +431,37 @@ describe 'Chef::Win32::Registry', :windows_only do context "registry constructor" do it "throws an exception if requested architecture is 64bit but running on 32bit" do - lambda {Chef::Win32::Registry.new(@run_context, :x86_64)}.should raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) + expect {Chef::Win32::Registry.new(@run_context, :x86_64)}.to raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) end it "can correctly set the requested architecture to 32-bit" do @r = Chef::Win32::Registry.new(@run_context, :i386) - @r.architecture.should == :i386 - @r.registry_system_architecture.should == 0x0200 + expect(@r.architecture).to eq(:i386) + expect(@r.registry_system_architecture).to eq(0x0200) end it "can correctly set the requested architecture to :machine" do @r = Chef::Win32::Registry.new(@run_context, :machine) - @r.architecture.should == :machine - @r.registry_system_architecture.should == 0x0200 + expect(@r.architecture).to eq(:machine) + expect(@r.registry_system_architecture).to eq(0x0200) end end context "architecture setter" do it "throws an exception if requested architecture is 64bit but running on 32bit" do - lambda {@registry.architecture = :x86_64}.should raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) + expect {@registry.architecture = :x86_64}.to raise_error(Chef::Exceptions::Win32RegArchitectureIncorrect) end it "sets the requested architecture to :machine if passed :machine" do @registry.architecture = :machine - @registry.architecture.should == :machine - @registry.registry_system_architecture.should == 0x0200 + expect(@registry.architecture).to eq(:machine) + expect(@registry.registry_system_architecture).to eq(0x0200) end it "sets the requested architecture to 32-bit if passed i386 as a string" do @registry.architecture = :i386 - @registry.architecture.should == :i386 - @registry.registry_system_architecture.should == 0x0200 + expect(@registry.architecture).to eq(:i386) + expect(@registry.registry_system_architecture).to eq(0x0200) end end end @@ -479,40 +479,40 @@ describe 'Chef::Win32::Registry', :windows_only do context "registry constructor" do it "can correctly set the requested architecture to 32-bit" do @r = Chef::Win32::Registry.new(@run_context, :i386) - @r.architecture.should == :i386 - @r.registry_system_architecture.should == 0x0200 + expect(@r.architecture).to eq(:i386) + expect(@r.registry_system_architecture).to eq(0x0200) end it "can correctly set the requested architecture to 64-bit" do @r = Chef::Win32::Registry.new(@run_context, :x86_64) - @r.architecture.should == :x86_64 - @r.registry_system_architecture.should == 0x0100 + expect(@r.architecture).to eq(:x86_64) + expect(@r.registry_system_architecture).to eq(0x0100) end it "can correctly set the requested architecture to :machine" do @r = Chef::Win32::Registry.new(@run_context, :machine) - @r.architecture.should == :machine - @r.registry_system_architecture.should == 0x0100 + expect(@r.architecture).to eq(:machine) + expect(@r.registry_system_architecture).to eq(0x0100) end end context "architecture setter" do it "sets the requested architecture to 64-bit if passed 64-bit" do @registry.architecture = :x86_64 - @registry.architecture.should == :x86_64 - @registry.registry_system_architecture.should == 0x0100 + expect(@registry.architecture).to eq(:x86_64) + expect(@registry.registry_system_architecture).to eq(0x0100) end it "sets the requested architecture to :machine if passed :machine" do @registry.architecture = :machine - @registry.architecture.should == :machine - @registry.registry_system_architecture.should == 0x0100 + expect(@registry.architecture).to eq(:machine) + expect(@registry.registry_system_architecture).to eq(0x0100) end it "sets the requested architecture to 32-bit if passed 32-bit" do @registry.architecture = :i386 - @registry.architecture.should == :i386 - @registry.registry_system_architecture.should == 0x0200 + expect(@registry.architecture).to eq(:i386) + expect(@registry.registry_system_architecture).to eq(0x0200) end end end @@ -555,75 +555,75 @@ describe 'Chef::Win32::Registry', :windows_only do describe "key_exists?" do it "does not find 64-bit keys in the 32-bit registry" do @registry.architecture=:i386 - @registry.key_exists?("HKLM\\Software\\Root\\Mauve").should == false + expect(@registry.key_exists?("HKLM\\Software\\Root\\Mauve")).to eq(false) end it "finds 32-bit keys in the 32-bit registry" do @registry.architecture=:i386 - @registry.key_exists?("HKLM\\Software\\Root\\Poosh").should == true + expect(@registry.key_exists?("HKLM\\Software\\Root\\Poosh")).to eq(true) end it "does not find 32-bit keys in the 64-bit registry" do @registry.architecture=:x86_64 - @registry.key_exists?("HKLM\\Software\\Root\\Mauve").should == true + expect(@registry.key_exists?("HKLM\\Software\\Root\\Mauve")).to eq(true) end it "finds 64-bit keys in the 64-bit registry" do @registry.architecture=:x86_64 - @registry.key_exists?("HKLM\\Software\\Root\\Poosh").should == false + expect(@registry.key_exists?("HKLM\\Software\\Root\\Poosh")).to eq(false) end end describe "value_exists?" do it "does not find 64-bit values in the 32-bit registry" do @registry.architecture=:i386 - lambda{@registry.value_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert"})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect{@registry.value_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "finds 32-bit values in the 32-bit registry" do @registry.architecture=:i386 - @registry.value_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status"}).should == true + expect(@registry.value_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status"})).to eq(true) end it "does not find 32-bit values in the 64-bit registry" do @registry.architecture=:x86_64 - @registry.value_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert"}).should == true + expect(@registry.value_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert"})).to eq(true) end it "finds 64-bit values in the 64-bit registry" do @registry.architecture=:x86_64 - lambda{@registry.value_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status"})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect{@registry.value_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end describe "data_exists?" do it "does not find 64-bit keys in the 32-bit registry" do @registry.architecture=:i386 - lambda{@registry.data_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert", :type=>:string, :data=>"Universal"})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect{@registry.data_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert", :type=>:string, :data=>"Universal"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "finds 32-bit keys in the 32-bit registry" do @registry.architecture=:i386 - @registry.data_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status", :type=>:string, :data=>"Lost"}).should == true + expect(@registry.data_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status", :type=>:string, :data=>"Lost"})).to eq(true) end it "does not find 32-bit keys in the 64-bit registry" do @registry.architecture=:x86_64 - @registry.data_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert", :type=>:string, :data=>"Universal"}).should == true + expect(@registry.data_exists?("HKLM\\Software\\Root\\Mauve", {:name=>"Alert", :type=>:string, :data=>"Universal"})).to eq(true) end it "finds 64-bit keys in the 64-bit registry" do @registry.architecture=:x86_64 - lambda{@registry.data_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status", :type=>:string, :data=>"Lost"})}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect{@registry.data_exists?("HKLM\\Software\\Root\\Poosh", {:name=>"Status", :type=>:string, :data=>"Lost"})}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end describe "create_key" do it "can create a 32-bit only registry key" do @registry.architecture = :i386 - @registry.create_key("HKLM\\Software\\Root\\Trunk\\Red", true).should == true - @registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Red").should == true + expect(@registry.create_key("HKLM\\Software\\Root\\Trunk\\Red", true)).to eq(true) + expect(@registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Red")).to eq(true) @registry.architecture = :x86_64 - @registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Red").should == false + expect(@registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Red")).to eq(false) end it "can create a 64-bit only registry key" do @registry.architecture = :x86_64 - @registry.create_key("HKLM\\Software\\Root\\Trunk\\Blue", true).should == true - @registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Blue").should == true + expect(@registry.create_key("HKLM\\Software\\Root\\Trunk\\Blue", true)).to eq(true) + expect(@registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Blue")).to eq(true) @registry.architecture = :i386 - @registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Blue").should == false + expect(@registry.key_exists?("HKLM\\Software\\Root\\Trunk\\Blue")).to eq(false) end end diff --git a/spec/functional/win32/security_spec.rb b/spec/functional/win32/security_spec.rb index 4ad9b07b74..010a4ca557 100644 --- a/spec/functional/win32/security_spec.rb +++ b/spec/functional/win32/security_spec.rb @@ -23,7 +23,7 @@ end describe 'Chef::Win32::Security', :windows_only do it "has_admin_privileges? returns true when running as admin" do - Chef::ReservedNames::Win32::Security.has_admin_privileges?.should == true + expect(Chef::ReservedNames::Win32::Security.has_admin_privileges?).to eq(true) end # We've done some investigation adding a negative test and it turned @@ -32,6 +32,6 @@ describe 'Chef::Win32::Security', :windows_only do # # TODO - Add negative tests once mixlib-shellout has user support it "has_admin_privileges? returns false when running as non-admin" do - pending "requires user support in mixlib-shellout" + skip "requires user support in mixlib-shellout" end end diff --git a/spec/functional/win32/service_manager_spec.rb b/spec/functional/win32/service_manager_spec.rb index b5b2e20825..fd21e7d82e 100644 --- a/spec/functional/win32/service_manager_spec.rb +++ b/spec/functional/win32/service_manager_spec.rb @@ -93,7 +93,7 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind context "with invalid service definition" do it "throws an error when initialized with no service definition" do - lambda { Chef::Application::WindowsServiceManager.new(nil) }.should raise_error(ArgumentError) + expect { Chef::Application::WindowsServiceManager.new(nil) }.to raise_error(ArgumentError) end it "throws an error with required missing options" do @@ -101,7 +101,7 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind service_def = test_service.dup service_def.delete(key) - lambda { Chef::Application::WindowsServiceManager.new(service_def) }.should raise_error(ArgumentError) + expect { Chef::Application::WindowsServiceManager.new(service_def) }.to raise_error(ArgumentError) end end end @@ -111,7 +111,7 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind @service_manager_output = [ ] # Uncomment below lines to debug this test # original_puts = $stdout.method(:puts) - $stdout.stub(:puts) do |message| + allow($stdout).to receive(:puts) do |message| @service_manager_output << message # original_puts.call(message) end @@ -125,19 +125,19 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind it "default => should say service don't exist" do service_manager.run - @service_manager_output.grep(/doesn't exist on the system/).length.should > 0 + expect(@service_manager_output.grep(/doesn't exist on the system/).length).to be > 0 end it "install => should install the service" do service_manager.run(["-a", "install"]) - test_service_exists?.should be_true + expect(test_service_exists?).to be_truthy end it "other actions => should say service doesn't exist" do ["delete", "start", "stop", "pause", "resume", "uninstall"].each do |action| service_manager.run(["-a", action]) - @service_manager_output.grep(/doesn't exist on the system/).length.should > 0 + expect(@service_manager_output.grep(/doesn't exist on the system/).length).to be > 0 @service_manager_output = [ ] end end @@ -150,47 +150,47 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind it "should have an own-process, non-interactive type" do status = ::Win32::Service.status("spec-service") - status[:service_type].should == "own process" - status[:interactive].should be_false + expect(status[:service_type]).to eq("own process") + expect(status[:interactive]).to be_falsey end it "install => should say service already exists" do service_manager.run(["-a", "install"]) - @service_manager_output.grep(/already exists/).length.should > 0 + expect(@service_manager_output.grep(/already exists/).length).to be > 0 end context "and service is stopped" do ["delete", "uninstall"].each do |action| it "#{action} => should remove the service", :volatile do service_manager.run(["-a", action]) - test_service_exists?.should be_false + expect(test_service_exists?).to be_falsey end end it "default, status => should say service is stopped" do service_manager.run([ ]) - @service_manager_output.grep(/stopped/).length.should > 0 + expect(@service_manager_output.grep(/stopped/).length).to be > 0 @service_manager_output = [ ] service_manager.run(["-a", "status"]) - @service_manager_output.grep(/stopped/).length.should > 0 + expect(@service_manager_output.grep(/stopped/).length).to be > 0 end it "start should start the service", :volatile do service_manager.run(["-a", "start"]) - test_service_state.should == "running" - File.exists?(test_service_file).should be_true + expect(test_service_state).to eq("running") + expect(File.exists?(test_service_file)).to be_truthy end it "stop should not affect the service" do service_manager.run(["-a", "stop"]) - test_service_state.should == "stopped" + expect(test_service_state).to eq("stopped") end ["pause", "resume"].each do |action| it "#{action} => should raise error" do - lambda {service_manager.run(["-a", action])}.should raise_error(::Win32::Service::Error) + expect {service_manager.run(["-a", action])}.to raise_error(::Win32::Service::Error) end end @@ -202,32 +202,32 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind ["delete", "uninstall"].each do |action| it "#{action} => should remove the service", :volatile do service_manager.run(["-a", action]) - test_service_exists?.should be_false + expect(test_service_exists?).to be_falsey end end it "default, status => should say service is running" do service_manager.run([ ]) - @service_manager_output.grep(/running/).length.should > 0 + expect(@service_manager_output.grep(/running/).length).to be > 0 @service_manager_output = [ ] service_manager.run(["-a", "status"]) - @service_manager_output.grep(/running/).length.should > 0 + expect(@service_manager_output.grep(/running/).length).to be > 0 end it "stop should stop the service" do service_manager.run(["-a", "stop"]) - test_service_state.should == "stopped" + expect(test_service_state).to eq("stopped") end it "pause should pause the service" do service_manager.run(["-a", "pause"]) - test_service_state.should == "paused" + expect(test_service_state).to eq("paused") end it "resume should have no affect" do service_manager.run(["-a", "resume"]) - test_service_state.should == "running" + expect(test_service_state).to eq("running") end end @@ -241,31 +241,31 @@ describe "Chef::Application::WindowsServiceManager", :windows_only, :system_wind actions.each do |action| it "#{action} => should remove the service" do service_manager.run(["-a", action]) - test_service_exists?.should be_false + expect(test_service_exists?).to be_falsey end end it "default, status => should say service is paused" do service_manager.run([ ]) - @service_manager_output.grep(/paused/).length.should > 0 + expect(@service_manager_output.grep(/paused/).length).to be > 0 @service_manager_output = [ ] service_manager.run(["-a", "status"]) - @service_manager_output.grep(/paused/).length.should > 0 + expect(@service_manager_output.grep(/paused/).length).to be > 0 end it "stop should stop the service" do service_manager.run(["-a", "stop"]) - test_service_state.should == "stopped" + expect(test_service_state).to eq("stopped") end it "pause should not affect the service" do service_manager.run(["-a", "pause"]) - test_service_state.should == "paused" + expect(test_service_state).to eq("paused") end it "start should raise an error" do - lambda {service_manager.run(["-a", "start"])}.should raise_error(::Win32::Service::Error) + expect {service_manager.run(["-a", "start"])}.to raise_error(::Win32::Service::Error) end end diff --git a/spec/functional/win32/versions_spec.rb b/spec/functional/win32/versions_spec.rb index 6c8f6b2aaa..38af47b0c9 100644 --- a/spec/functional/win32/versions_spec.rb +++ b/spec/functional/win32/versions_spec.rb @@ -62,8 +62,8 @@ describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on it "should have have one method for each marketing version" do versions = 0 for_each_windows_version { versions += 1 } - versions.should > 0 - versions.should == Chef::ReservedNames::Win32::Version::WIN_VERSIONS.length + expect(versions).to be > 0 + expect(versions).to eq(Chef::ReservedNames::Win32::Version::WIN_VERSIONS.length) end it "should only contain version methods with legal method names" do @@ -71,8 +71,8 @@ describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on for_each_windows_version do |method_name| method_match = method_name_pattern.match(method_name.to_s) - method_match.should_not be_nil - method_name.to_s.should == method_match[0] + expect(method_match).not_to be_nil + expect(method_name.to_s).to eq(method_match[0]) end end @@ -81,7 +81,7 @@ describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on for_each_windows_version do |method_name| true_versions += 1 if @version.send(method_name) end - true_versions.should == 1 + expect(true_versions).to eq(1) end it "should successfully execute all version methods" do @@ -91,7 +91,7 @@ describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on context "Windows Operating System version" do it "should match the version from WMI" do - @current_os_version.should include(@version.marketing_name) + expect(@current_os_version).to include(@version.marketing_name) end end diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb index 0144ae0ce3..f4bb124781 100644 --- a/spec/integration/client/client_spec.rb +++ b/spec/integration/client/client_spec.rb @@ -44,7 +44,7 @@ EOM it 'should fail when cwd is below high above and paths are not specified' do result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => File.expand_path('..', path_to(''))) - result.exitstatus.should == 1 + expect(result.exitstatus).to eq(1) end end @@ -54,7 +54,7 @@ EOM it 'should load .chef/knife.rb when -z is specified' do result = shell_out("#{chef_client} -z -o 'x::default'", :cwd => path_to('')) # FATAL: Configuration error NoMethodError: undefined method `xxx' for nil:NilClass - result.stdout.should include("xxx") + expect(result.stdout).to include("xxx") end end @@ -135,8 +135,8 @@ EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" #{path_to('arbitrary.rb')} #{path_to('arbitrary2.rb')}", :cwd => chef_dir) result.error! - IO.read(path_to('tempfile.txt')).should == '1' - IO.read(path_to('tempfile2.txt')).should == '2' + expect(IO.read(path_to('tempfile.txt'))).to eq('1') + expect(IO.read(path_to('tempfile2.txt'))).to eq('2') end it "should run recipes specified as relative paths directly on the command line" do @@ -155,7 +155,7 @@ EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" arbitrary.rb", :cwd => path_to('')) result.error! - IO.read(path_to('tempfile.txt')).should == '1' + expect(IO.read(path_to('tempfile.txt'))).to eq('1') end it "should run recipes specified directly on the command line AFTER recipes in the run list" do @@ -179,7 +179,7 @@ EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o x::constant_definition arbitrary.rb", :cwd => path_to('')) result.error! - IO.read(path_to('tempfile.txt')).should == '1' + expect(IO.read(path_to('tempfile.txt'))).to eq('1') end end @@ -211,7 +211,7 @@ cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", :cwd => chef_dir) - result.stdout.should_not include("SSL validation of HTTPS requests is disabled.") + expect(result.stdout).not_to include("SSL validation of HTTPS requests is disabled.") result.error! end @@ -232,8 +232,8 @@ cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -r 'x::default' -z", :cwd => chef_dir) - result.stdout.should_not include("Overridden Run List") - result.stdout.should include("Run List is [recipe[x::default]]") + expect(result.stdout).not_to include("Overridden Run List") + expect(result.stdout).to include("Run List is [recipe[x::default]]") #puts result.stdout result.error! end diff --git a/spec/integration/knife/chef_fs_data_store_spec.rb b/spec/integration/knife/chef_fs_data_store_spec.rb index a4d62673de..eb02db5384 100644 --- a/spec/integration/knife/chef_fs_data_store_spec.rb +++ b/spec/integration/knife/chef_fs_data_store_spec.rb @@ -180,9 +180,9 @@ EOM knife('list --local /users').should_succeed "/users/x.json\n" end - it 'After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty', :pending => (RUBY_VERSION < "1.9") do + it 'After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty', :skip => (RUBY_VERSION < "1.9") do knife("raw -z -i #{path_to('rolestuff.json')} -m PUT /roles/x").should_succeed( /"x"/ ) - IO.read(path_to('roles/x.json')).should == <<EOM.strip + expect(IO.read(path_to('roles/x.json'))).to eq <<EOM.strip { "name": "x", "description": "hi there" @@ -246,9 +246,9 @@ EOM knife('list --local /users').should_succeed "/users/z.json\n" end - it 'After knife raw -z -i rolestuff.json -m POST /roles, the output is pretty', :pending => (RUBY_VERSION < "1.9") do + it 'After knife raw -z -i rolestuff.json -m POST /roles, the output is pretty', :skip => (RUBY_VERSION < "1.9") do knife("raw -z -i #{path_to('rolestuff.json')} -m POST /roles").should_succeed( /uri/ ) - IO.read(path_to('roles/x.json')).should == <<EOM.strip + expect(IO.read(path_to('roles/x.json'))).to eq <<EOM.strip { "name": "x", "description": "hi there" diff --git a/spec/integration/knife/common_options_spec.rb b/spec/integration/knife/common_options_spec.rb index dfc1e024f9..ec76738b6f 100644 --- a/spec/integration/knife/common_options_spec.rb +++ b/spec/integration/knife/common_options_spec.rb @@ -39,7 +39,7 @@ describe 'knife common options', :workstation do it 'knife raw /nodes/x should retrieve the node' do knife('raw /nodes/x').should_succeed( /"name": "x"/ ) - Chef::Config.chef_server_url.should == 'http://localhost:9999' + expect(Chef::Config.chef_server_url).to eq('http://localhost:9999') end end @@ -101,7 +101,7 @@ EOM it 'knife raw -z --chef-zero-port=9999 /nodes/x retrieves the node' do knife('raw -z --chef-zero-port=9999 /nodes/x').should_succeed( /"name": "x"/ ) - Chef::Config.chef_server_url.should == 'http://localhost:9999' + expect(Chef::Config.chef_server_url).to eq('http://localhost:9999') end context 'when the default port (8889) is already bound' do @@ -149,7 +149,7 @@ EOM it 'knife raw -z --chef-zero-port=9999 /nodes/x retrieves the node' do knife('raw -z --chef-zero-port=9999 /nodes/x').should_succeed( /"name": "x"/ ) - Chef::Config.chef_server_url.should == 'http://localhost:9999' + expect(Chef::Config.chef_server_url).to eq('http://localhost:9999') end end end diff --git a/spec/integration/knife/cookbook_api_ipv6_spec.rb b/spec/integration/knife/cookbook_api_ipv6_spec.rb index e59c8912bd..3d468be7f6 100644 --- a/spec/integration/knife/cookbook_api_ipv6_spec.rb +++ b/spec/integration/knife/cookbook_api_ipv6_spec.rb @@ -92,7 +92,7 @@ END_CLIENT_RB shell_out!("#{knife} cookbook upload apache2 #{knife_config_flag}", :cwd => chef_dir) versions_list_json = Chef::HTTP::Simple.new("http://[::1]:8900").get("/cookbooks/apache2", "accept" => "application/json") versions_list = Chef::JSONCompat.from_json(versions_list_json) - versions_list["apache2"]["versions"].should_not be_empty + expect(versions_list["apache2"]["versions"]).not_to be_empty end context "and the cookbook has been uploaded to the server" do @@ -102,7 +102,7 @@ END_CLIENT_RB it "downloads the cookbook" do shell_out!("knife cookbook download apache2 #{knife_config_flag} -d #{cache_path}", :cwd => chef_dir) - Dir["#{cache_path}/*"].map {|entry| File.basename(entry)}.should include("apache2-0.0.1") + expect(Dir["#{cache_path}/*"].map {|entry| File.basename(entry)}).to include("apache2-0.0.1") end end diff --git a/spec/integration/knife/deps_spec.rb b/spec/integration/knife/deps_spec.rb index 8b4d71906b..3120db4940 100644 --- a/spec/integration/knife/deps_spec.rb +++ b/spec/integration/knife/deps_spec.rb @@ -251,8 +251,8 @@ EOM end it 'knife deps --tree prints each once' do knife('deps --tree /roles/foo.json /roles/self.json') do - stdout.should == "/roles/foo.json\n /roles/bar.json\n /roles/baz.json\n /roles/foo.json\n/roles/self.json\n /roles/self.json\n" - stderr.should == "WARNING: No knife configuration file found\n" + expect(stdout).to eq("/roles/foo.json\n /roles/bar.json\n /roles/baz.json\n /roles/foo.json\n/roles/self.json\n /roles/self.json\n") + expect(stderr).to eq("WARNING: No knife configuration file found\n") end end end @@ -589,8 +589,8 @@ EOM end it 'knife deps --tree prints each once' do knife('deps --remote --tree /roles/foo.json /roles/self.json') do - stdout.should == "/roles/foo.json\n /roles/bar.json\n /roles/baz.json\n /roles/foo.json\n/roles/self.json\n /roles/self.json\n" - stderr.should == "WARNING: No knife configuration file found\n" + expect(stdout).to eq("/roles/foo.json\n /roles/bar.json\n /roles/baz.json\n /roles/foo.json\n/roles/self.json\n /roles/self.json\n") + expect(stderr).to eq("WARNING: No knife configuration file found\n") end end end diff --git a/spec/integration/knife/diff_spec.rb b/spec/integration/knife/diff_spec.rb index c12ebbcf8f..465383437f 100644 --- a/spec/integration/knife/diff_spec.rb +++ b/spec/integration/knife/diff_spec.rb @@ -247,7 +247,7 @@ EOM end when_the_chef_server 'has an environment with a different value' do before { environment 'x', { 'description' => 'hi' } } - it 'knife diff reports the difference', :pending => (RUBY_VERSION < "1.9") do + it 'knife diff reports the difference', :skip => (RUBY_VERSION < "1.9") do knife('diff /environments/x.json').should_succeed(/ { - "name": "x", @@ -277,7 +277,7 @@ EOM environment 'x', {} end - it 'knife diff reports the difference', :pending => (RUBY_VERSION < "1.9") do + it 'knife diff reports the difference', :skip => (RUBY_VERSION < "1.9") do knife('diff /environments/x.json').should_succeed(/ { - "name": "x" @@ -291,7 +291,7 @@ EOM before do environment 'x', { 'description' => 'lo' } end - it 'knife diff reports the difference', :pending => (RUBY_VERSION < "1.9") do + it 'knife diff reports the difference', :skip => (RUBY_VERSION < "1.9") do knife('diff /environments/x.json').should_succeed(/ { "name": "x", @@ -533,7 +533,7 @@ EOM end when_the_chef_server 'has an environment with a different value' do before { environment 'x', { 'description' => 'hi' } } - it 'knife diff reports the difference', :pending => (RUBY_VERSION < "1.9") do + it 'knife diff reports the difference', :skip => (RUBY_VERSION < "1.9") do knife('diff /environments/x.json').should_succeed(/ { - "name": "x", @@ -560,7 +560,7 @@ EOM end when_the_chef_server 'has an environment with no value' do before { environment 'x', {} } - it 'knife diff reports the difference', :pending => (RUBY_VERSION < "1.9") do + it 'knife diff reports the difference', :skip => (RUBY_VERSION < "1.9") do knife('diff /environments/x.json').should_succeed(/ { - "name": "x" @@ -574,7 +574,7 @@ EOM before do environment 'x', { 'description' => 'lo' } end - it 'knife diff reports the difference', :pending => (RUBY_VERSION < "1.9") do + it 'knife diff reports the difference', :skip => (RUBY_VERSION < "1.9") do knife('diff /environments/x.json').should_succeed(/ { "name": "x", diff --git a/spec/integration/knife/download_spec.rb b/spec/integration/knife/download_spec.rb index 0c2b907f1e..cf1e4fcf0f 100644 --- a/spec/integration/knife/download_spec.rb +++ b/spec/integration/knife/download_spec.rb @@ -1073,15 +1073,15 @@ EOM # Check that BasicClient.request() always gets called with X-OPS-USERID original_new = Chef::HTTP::BasicClient.method(:new) - Chef::HTTP::BasicClient.should_receive(:new) do |args| + expect(Chef::HTTP::BasicClient).to receive(:new) { |args| new_result = original_new.call(*args) original_request = new_result.method(:request) - new_result.should_receive(:request) do |method, url, body, headers, &response_handler| - headers['X-OPS-USERID'].should_not be_nil + expect(new_result).to receive(:request) { |method, url, body, headers, &response_handler| + expect(headers['X-OPS-USERID']).not_to be_nil original_request.call(method, url, body, headers, &response_handler) - end.at_least(:once) + }.at_least(:once) new_result - end.at_least(:once) + }.at_least(:once) knife('download /cookbooks/x').should_succeed <<EOM Created /cookbooks diff --git a/spec/integration/knife/list_spec.rb b/spec/integration/knife/list_spec.rb index 3d8b83001d..911b56ef18 100644 --- a/spec/integration/knife/list_spec.rb +++ b/spec/integration/knife/list_spec.rb @@ -471,7 +471,7 @@ EOM end end - when_the_repository 'has a cookbooks directory and a symlinked cookbooks directory', :pending => (Chef::Platform.windows?) do + when_the_repository 'has a cookbooks directory and a symlinked cookbooks directory', :skip => (Chef::Platform.windows?) do before do directory 'cookbooks' symlink 'symlinked', 'cookbooks' @@ -508,7 +508,7 @@ EOM end end - when_the_repository 'has a real_cookbooks directory and a cookbooks symlink to it', :pending => (Chef::Platform.windows?) do + when_the_repository 'has a real_cookbooks directory and a cookbooks symlink to it', :skip => (Chef::Platform.windows?) do before do directory 'real_cookbooks' symlink 'cookbooks', 'real_cookbooks' diff --git a/spec/integration/knife/raw_spec.rb b/spec/integration/knife/raw_spec.rb index 2b49d2ebb2..75fc8fa55e 100644 --- a/spec/integration/knife/raw_spec.rb +++ b/spec/integration/knife/raw_spec.rb @@ -38,7 +38,7 @@ describe 'knife raw', :workstation do user 'x', '{}' end - it 'knife raw /nodes/x returns the node', :pending => (RUBY_VERSION < "1.9") do + it 'knife raw /nodes/x returns the node', :skip => (RUBY_VERSION < "1.9") do knife('raw /nodes/x').should_succeed <<EOM { "name": "x", @@ -68,7 +68,7 @@ EOM knife('raw /blarghle').should_fail(/ERROR: Server responded with error 404 "Not Found\s*"/) end - it 'knife raw -m DELETE /roles/x succeeds', :pending => (RUBY_VERSION < "1.9") do + it 'knife raw -m DELETE /roles/x succeeds', :skip => (RUBY_VERSION < "1.9") do knife('raw -m DELETE /roles/x').should_succeed <<EOM { "name": "x", @@ -92,7 +92,7 @@ EOM knife('show /roles/x.json').should_fail "ERROR: /roles/x.json: No such file or directory\n" end - it 'knife raw -m PUT -i blah.txt /roles/x succeeds', :pending => (RUBY_VERSION < "1.9") do + it 'knife raw -m PUT -i blah.txt /roles/x succeeds', :skip => (RUBY_VERSION < "1.9") do Tempfile.open('raw_put_input') do |file| file.write <<EOM { @@ -146,7 +146,7 @@ EOM end end - it 'knife raw -m POST -i blah.txt /roles succeeds', :pending => (RUBY_VERSION < "1.9") do + it 'knife raw -m POST -i blah.txt /roles succeeds', :skip => (RUBY_VERSION < "1.9") do Tempfile.open('raw_put_input') do |file| file.write <<EOM { @@ -196,7 +196,7 @@ EOM @raw_server_thread.kill if @raw_server_thread end - it 'knife raw /blah returns the prettified json', :pending => (RUBY_VERSION < "1.9") do + it 'knife raw /blah returns the prettified json', :skip => (RUBY_VERSION < "1.9") do knife('raw /blah').should_succeed <<EOM { "x": "y", diff --git a/spec/integration/knife/serve_spec.rb b/spec/integration/knife/serve_spec.rb index 6a8328ef9e..7bf7d29b40 100644 --- a/spec/integration/knife/serve_spec.rb +++ b/spec/integration/knife/serve_spec.rb @@ -42,7 +42,7 @@ describe 'knife serve', :workstation do Chef::Config.node_name = nil Chef::Config.client_key = nil api = Chef::ServerAPI.new - api.get('nodes/x')['name'].should == 'x' + expect(api.get('nodes/x')['name']).to eq('x') rescue if exception raise exception diff --git a/spec/integration/knife/show_spec.rb b/spec/integration/knife/show_spec.rb index bc7f1cf6d3..8f1887e738 100644 --- a/spec/integration/knife/show_spec.rb +++ b/spec/integration/knife/show_spec.rb @@ -76,7 +76,7 @@ EOM } EOM end - it 'knife show /environments/x.json shows the remote version', :pending => (RUBY_VERSION < "1.9") do + it 'knife show /environments/x.json shows the remote version', :skip => (RUBY_VERSION < "1.9") do knife('show /environments/x.json').should_succeed <<EOM /environments/x.json: { @@ -92,7 +92,7 @@ EOM } EOM end - it 'knife show /roles/x.json shows the remote version', :pending => (RUBY_VERSION < "1.9") do + it 'knife show /roles/x.json shows the remote version', :skip => (RUBY_VERSION < "1.9") do knife('show /roles/x.json').should_succeed <<EOM /roles/x.json: { @@ -135,7 +135,7 @@ EOM 'name' => 'x' } end - it 'knife show shows the attributes in a predetermined order', :pending => (RUBY_VERSION < "1.9") do + it 'knife show shows the attributes in a predetermined order', :skip => (RUBY_VERSION < "1.9") do knife('show /environments/x.json').should_succeed <<EOM /environments/x.json: { diff --git a/spec/integration/knife/upload_spec.rb b/spec/integration/knife/upload_spec.rb index dade476889..cef4f54e97 100644 --- a/spec/integration/knife/upload_spec.rb +++ b/spec/integration/knife/upload_spec.rb @@ -262,7 +262,7 @@ Created /data_bags/x/y.json EOM knife('diff --name-status /data_bags').should_succeed <<EOM EOM - Chef::JSONCompat.parse(knife('raw /data/x/y').stdout, :create_additions => false).keys.sort.should == [ 'foo', 'id' ] + expect(Chef::JSONCompat.parse(knife('raw /data/x/y').stdout, :create_additions => false).keys.sort).to eq([ 'foo', 'id' ]) end it 'knife upload /data_bags/x /data_bags/x/y.json uploads x once' do @@ -286,9 +286,9 @@ Created /data_bags/x/y.json EOM knife('diff --name-status /data_bags').should_succeed '' result = Chef::JSONCompat.parse(knife('raw /data/x/y').stdout, :create_additions => false) - result.keys.sort.should == [ 'chef_type', 'data_bag', 'id' ] - result['chef_type'].should == 'aaa' - result['data_bag'].should == 'bbb' + expect(result.keys.sort).to eq([ 'chef_type', 'data_bag', 'id' ]) + expect(result['chef_type']).to eq('aaa') + expect(result['data_bag']).to eq('bbb') end end @@ -1268,8 +1268,8 @@ Created /nodes/x.json Updated /org.json Created /roles/x.json EOM - api.get('association_requests').map { |a| a['username'] }.should == [ 'foo' ] - api.get('users').map { |a| a['user']['username'] }.should == [ 'bar' ] + expect(api.get('association_requests').map { |a| a['username'] }).to eq([ 'foo' ]) + expect(api.get('users').map { |a| a['user']['username'] }).to eq([ 'bar' ]) end end @@ -1280,7 +1280,7 @@ EOM it 'knife upload / emits a warning for bar and adds foo and foobar' do knife('upload /').should_succeed '' - api.get('/')['full_name'].should == 'Something' + expect(api.get('/')['full_name']).to eq('Something') end end @@ -1291,7 +1291,7 @@ EOM it 'knife upload / emits a warning for bar and adds foo and foobar' do knife('upload /').should_succeed "Updated /org.json\n" - api.get('/')['full_name'].should == 'Something Else' + expect(api.get('/')['full_name']).to eq('Something Else') end end @@ -1306,8 +1306,8 @@ EOM it 'knife upload / emits a warning for bar and invites foobar' do knife('upload /').should_succeed "Updated /invitations.json\n", :stderr => "WARN: Could not invite bar to organization foo: User bar is already in organization foo\n" - api.get('association_requests').map { |a| a['username'] }.should == [ 'foo', 'foobar' ] - api.get('users').map { |a| a['user']['username'] }.should == [ 'bar' ] + expect(api.get('association_requests').map { |a| a['username'] }).to eq([ 'foo', 'foobar' ]) + expect(api.get('users').map { |a| a['user']['username'] }).to eq([ 'bar' ]) end end @@ -1318,8 +1318,8 @@ EOM it 'knife upload / emits a warning for bar and adds foo and foobar' do knife('upload /').should_succeed "Updated /members.json\n" - api.get('association_requests').map { |a| a['username'] }.should == [ ] - api.get('users').map { |a| a['user']['username'] }.should == [ 'bar', 'foo', 'foobar' ] + expect(api.get('association_requests').map { |a| a['username'] }).to eq([ ]) + expect(api.get('users').map { |a| a['user']['username'] }).to eq([ 'bar', 'foo', 'foobar' ]) end end @@ -1331,8 +1331,8 @@ EOM it 'knife upload / does nothing' do knife('upload /').should_succeed '' - api.get('association_requests').map { |a| a['username'] }.should == [ 'foo' ] - api.get('users').map { |a| a['user']['username'] }.should == [ 'bar' ] + expect(api.get('association_requests').map { |a| a['username'] }).to eq([ 'foo' ]) + expect(api.get('users').map { |a| a['user']['username'] }).to eq([ 'bar' ]) end end end @@ -1347,8 +1347,8 @@ EOM it 'knife upload / does nothing' do knife('upload /').should_succeed '' - api.get('association_requests').map { |a| a['username'] }.should == [ 'bar', 'foo' ] - api.get('users').map { |a| a['user']['username'] }.should == [ ] + expect(api.get('association_requests').map { |a| a['username'] }).to eq([ 'bar', 'foo' ]) + expect(api.get('users').map { |a| a['user']['username'] }).to eq([ ]) end end end @@ -1363,8 +1363,8 @@ EOM it 'knife upload / does nothing' do knife('upload /').should_succeed '' - api.get('association_requests').map { |a| a['username'] }.should == [ ] - api.get('users').map { |a| a['user']['username'] }.should == [ 'bar', 'foo' ] + expect(api.get('association_requests').map { |a| a['username'] }).to eq([ ]) + expect(api.get('users').map { |a| a['user']['username'] }).to eq([ 'bar', 'foo' ]) end end end diff --git a/spec/integration/recipes/lwrp_inline_resources_spec.rb b/spec/integration/recipes/lwrp_inline_resources_spec.rb index a0c13da6f7..a3baba8b0f 100644 --- a/spec/integration/recipes/lwrp_inline_resources_spec.rb +++ b/spec/integration/recipes/lwrp_inline_resources_spec.rb @@ -71,7 +71,7 @@ EOM (up to date) EOM expected = expected.lines.map { |l| l.chomp }.join("\n") - actual.should include(expected) + expect(actual).to include(expected) result.error! end end diff --git a/spec/integration/solo/solo_spec.rb b/spec/integration/solo/solo_spec.rb index 793789b754..cc9ba1abb2 100644 --- a/spec/integration/solo/solo_spec.rb +++ b/spec/integration/solo/solo_spec.rb @@ -28,7 +28,7 @@ file_cache_path "#{path_to('config/cache')}" EOM result = shell_out("ruby bin/chef-solo -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", :cwd => chef_dir) result.error! - result.stdout.should include("ITWORKS") + expect(result.stdout).to include("ITWORKS") end it "should evaluate its node.json file" do @@ -43,7 +43,7 @@ E result = shell_out("ruby bin/chef-solo -c \"#{path_to('config/solo.rb')}\" -j '#{path_to('config/node.json')}' -l debug", :cwd => chef_dir) result.error! - result.stdout.should include("ITWORKS") + expect(result.stdout).to include("ITWORKS") end end @@ -63,8 +63,8 @@ cookbook_path "#{path_to('cookbooks')}" file_cache_path "#{path_to('config/cache')}" EOM result = shell_out("ruby bin/chef-solo -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", :cwd => chef_dir) - result.exitstatus.should == 0 # For CHEF-5120 this becomes 1 - result.stdout.should include("WARN: MissingCookbookDependency") + expect(result.exitstatus).to eq(0) # For CHEF-5120 this becomes 1 + expect(result.stdout).to include("WARN: MissingCookbookDependency") end end @@ -91,7 +91,7 @@ file_cache_path "#{path_to('config/cache')}" EOM # We have a timeout protection here so that if due to some bug # run_lock gets stuck we can discover it. - lambda { + expect { Timeout.timeout(120) do chef_dir = File.join(File.dirname(__FILE__), "..", "..", "..") @@ -109,7 +109,7 @@ EOM Process.waitpid(s1) Process.waitpid(s2) end - }.should_not raise_error + }.not_to raise_error # Unfortunately file / directory helpers in integration tests # are implemented using before(:each) so we need to do all below @@ -117,13 +117,13 @@ EOM run_log = File.read(path_to('logs/runs.log')) # both of the runs should succeed - run_log.lines.reject {|l| !l.include? "INFO: Chef Run complete in"}.length.should == 2 + expect(run_log.lines.reject {|l| !l.include? "INFO: Chef Run complete in"}.length).to eq(2) # second run should have a message which indicates it's waiting for the first run pid_lines = run_log.lines.reject {|l| !l.include? "Chef-client pid:"} - pid_lines.length.should == 2 + expect(pid_lines.length).to eq(2) pids = pid_lines.map {|l| l.split(" ").last} - run_log.should include("Chef client #{pids[0]} is running, will wait for it to finish and then run.") + expect(run_log).to include("Chef client #{pids[0]} is running, will wait for it to finish and then run.") # second run should start after first run ends starts = [ ] @@ -135,7 +135,7 @@ EOM ends << index end end - starts[1].should > ends[0] + expect(starts[1]).to be > ends[0] end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index cc5ba8c3ac..e3de80f3f1 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -18,12 +18,6 @@ # If you need to add anything in here, don't. # Add it to one of the files in spec/support -# Configure this first so it doesn't trigger annoying warning when we use it. -# Main rspec configuration comes later -RSpec.configure do |config| - config.treat_symbols_as_metadata_keys_with_true_values = true -end - # Abuse ruby's constant lookup to avoid undefined constant errors module Shell JUST_TESTING_MOVE_ALONG = true unless defined? JUST_TESTING_MOVE_ALONG @@ -97,6 +91,14 @@ RSpec.configure do |config| config.filter_run :focus => true config.filter_run_excluding :external => true + # Explicitly disable :should syntax + config.expect_with :rspec do |c| + c.syntax = :expect + end + config.mock_with :rspec do |c| + c.syntax = :expect + end + # Only run these tests on platforms that are also chef workstations config.filter_run_excluding :workstation if solaris? or aix? @@ -159,7 +161,6 @@ RSpec.configure do |config| } config.run_all_when_everything_filtered = true - config.treat_symbols_as_metadata_keys_with_true_values = true config.before(:each) do Chef::Config.reset diff --git a/spec/stress/win32/file_spec.rb b/spec/stress/win32/file_spec.rb index caeab352f7..dd1dcd305e 100644 --- a/spec/stress/win32/file_spec.rb +++ b/spec/stress/win32/file_spec.rb @@ -26,12 +26,12 @@ describe 'Chef::ReservedNames::Win32::File', :windows_only do it "should not leak significant memory" do test = lambda { Chef::ReservedNames::Win32::File.symlink?(@path) } - test.should_not leak_memory(:warmup => 50000, :iterations => 50000) + expect(test).not_to leak_memory(:warmup => 50000, :iterations => 50000) end it "should not leak handles" do test = lambda { Chef::ReservedNames::Win32::File.symlink?(@path) } - test.should_not leak_handles(:warmup => 50, :iterations => 100) + expect(test).not_to leak_handles(:warmup => 50, :iterations => 100) end end diff --git a/spec/stress/win32/security_spec.rb b/spec/stress/win32/security_spec.rb index e506b71be1..cb520e515e 100644 --- a/spec/stress/win32/security_spec.rb +++ b/spec/stress/win32/security_spec.rb @@ -49,21 +49,21 @@ describe 'Chef::ReservedNames::Win32::Security', :windows_only do end it "should not leak when retrieving and reading the ACE from a file", :volatile do - lambda { + expect { sids = Chef::ReservedNames::Win32::Security::SecurableObject.new(@monkeyfoo).security_descriptor.dacl.select { |ace| ace.sid } GC.start - }.should_not leak_memory(:warmup => 50, :iterations => 100) + }.not_to leak_memory(:warmup => 50, :iterations => 100) end it "should not leak when creating a new ACL and setting it on a file", :volatile do securable_object = Security::SecurableObject.new(@monkeyfoo) - lambda { + expect { securable_object.dacl = Chef::ReservedNames::Win32::Security::ACL.create([ Chef::ReservedNames::Win32::Security::ACE.access_allowed(Chef::ReservedNames::Win32::Security::SID.Everyone, Chef::ReservedNames::Win32::API::Security::GENERIC_READ), Chef::ReservedNames::Win32::Security::ACE.access_denied(Chef::ReservedNames::Win32::Security::SID.from_account("Users"), Chef::ReservedNames::Win32::API::Security::GENERIC_ALL) ]) GC.start - }.should_not leak_memory(:warmup => 50, :iterations => 100) + }.not_to leak_memory(:warmup => 50, :iterations => 100) end end diff --git a/spec/support/matchers/leak.rb b/spec/support/matchers/leak.rb index cc7d265a3c..01d1e53f92 100644 --- a/spec/support/matchers/leak.rb +++ b/spec/support/matchers/leak.rb @@ -26,11 +26,11 @@ module Matchers @variance = opts[:variance] || 5000 end - def failure_message_for_should + def failure_message "expected final measure [#{@final_measure}] to be greater than or within +/- #{@variance} delta of initial measure [#{@initial_measure}]" end - def failure_message_for_should_not + def failure_message_when_negated "expected final measure [#{@final_measure}] to be less than or within +/- #{@variance} delta of initial measure [#{@initial_measure}]" end diff --git a/spec/support/mock/platform.rb b/spec/support/mock/platform.rb index 46e76d48c5..ab2c19baff 100644 --- a/spec/support/mock/platform.rb +++ b/spec/support/mock/platform.rb @@ -6,7 +6,7 @@ # testing code that mixes in platform specific modules like +Chef::Mixin::Securable+ # or +Chef::FileAccessControl+ def platform_mock(platform = :unix, &block) - Chef::Platform.stub(:windows?).and_return(platform == :windows ? true : false) + allow(Chef::Platform).to receive(:windows?).and_return(platform == :windows ? true : false) ENV['SYSTEMDRIVE'] = (platform == :windows ? 'C:' : nil) if platform == :windows diff --git a/spec/support/pedant/Gemfile b/spec/support/pedant/Gemfile new file mode 100644 index 0000000000..d4224cd439 --- /dev/null +++ b/spec/support/pedant/Gemfile @@ -0,0 +1,3 @@ +source "https://rubygems.org" + +gem 'chef-pedant', :github => 'opscode/chef-pedant', :ref => "server-cli-option" diff --git a/spec/support/pedant/pedant_config.rb b/spec/support/pedant/pedant_config.rb index 6818d29d74..f7d14d8f17 100644 --- a/spec/support/pedant/pedant_config.rb +++ b/spec/support/pedant/pedant_config.rb @@ -72,6 +72,13 @@ superuser_name 'admin' superuser_key key webui_key key +# When we updated Chef to RSpec 3 there were gem conflicts with chef-pedant. +# We removed chef as a chef-pedant gem dependency in pedant.gemfile, but this +# caused chef-pedant to fail because it could not query for the chef version +# on the box pedant is running on. X-Chef-Version isn't needed in server +# requests for these tests, so we've disabled it. +ingore_x_chef_version true + # Set the platform_class platform_class Pedant::OpenSourcePlatform diff --git a/spec/support/pedant/run_pedant.rb b/spec/support/pedant/run_pedant.rb index abee67103c..aac2c2df1a 100644 --- a/spec/support/pedant/run_pedant.rb +++ b/spec/support/pedant/run_pedant.rb @@ -8,6 +8,7 @@ require 'chef/chef_fs/config' require 'tmpdir' require 'fileutils' require 'chef/version' +require 'chef/mixin/shell_out' def start_server(chef_repo_path) Dir.mkdir(chef_repo_path) if !File.exists?(chef_repo_path) @@ -37,28 +38,26 @@ begin # Capture setup data into master_chef_repo_path server = start_server(chef_repo_path) + so = nil - require 'pedant' - require 'pedant/opensource' + include Chef::Mixin::ShellOut - #Pedant::Config.rerun = true + Bundler.with_clean_env do - Pedant.config.suite = 'api' - Pedant.config[:config_file] = 'spec/support/pedant/pedant_config.rb' - Pedant.config.chef_server = server.url - Pedant.setup([ - '--skip-knife', - '--skip-validation', - '--skip-authentication', - '--skip-authorization', - '--skip-omnibus' - ]) + shell_out("bundle install --gemfile spec/support/pedant/Gemfile", :live_stream => STDOUT) - result = RSpec::Core::Runner.run(Pedant.config.rspec_args) + pedant_cmd = "chef-pedant " + + " --config spec/support/pedant/pedant_config.rb" + + " --server '#{server.url}'" + + " --skip-knife --skip-validation --skip-authentication" + + " --skip-authorization --skip-omnibus" + so = shell_out("bundle exec #{pedant_cmd}", :live_stream => STDOUT, :env => {'BUNDLE_GEMFILE' => 'spec/support/pedant/Gemfile'}) + + end - server.stop if server.running? ensure + server.stop if server && server.running? FileUtils.remove_entry_secure(tmpdir) if tmpdir end -exit(result) +exit(so.exitstatus) diff --git a/spec/support/shared/functional/directory_resource.rb b/spec/support/shared/functional/directory_resource.rb index ee9085424e..39bdc313e5 100644 --- a/spec/support/shared/functional/directory_resource.rb +++ b/spec/support/shared/functional/directory_resource.rb @@ -25,7 +25,7 @@ shared_examples_for "a directory resource" do context "when the target directory does not exist" do before do # assert pre-condition - File.should_not exist(path) + expect(File).not_to exist(path) end describe "when running action :create" do @@ -35,17 +35,17 @@ shared_examples_for "a directory resource" do end it "creates the directory when the :create action is run" do - File.should exist(path) + expect(File).to exist(path) end it "is marked updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end context "and the recursive option is set" do before do - File.should_not exist(path) + expect(File).not_to exist(path) resource.recursive(true) @recursive_path = File.join(path, 'red-headed-stepchild') @@ -54,12 +54,12 @@ shared_examples_for "a directory resource" do end it "recursively creates required directories" do - File.should exist(path) - File.should exist(@recursive_path) + expect(File).to exist(path) + expect(File).to exist(@recursive_path) end it "is marked updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end end @@ -97,7 +97,7 @@ shared_examples_for "a directory resource" do # so we run the resource twice--otherwise the updated_by_last_action test # will fail. resource.dup.run_action(:create) - File.should exist(path) + expect(File).to exist(path) resource.run_action(:create) end @@ -108,11 +108,11 @@ shared_examples_for "a directory resource" do end it "does not re-create the directory" do - File.should exist(path) + expect(File).to exist(path) end it "is not marked updated by last action" do - resource.should_not be_updated_by_last_action + expect(resource).not_to be_updated_by_last_action end end @@ -123,11 +123,11 @@ shared_examples_for "a directory resource" do end it "deletes the directory" do - File.should_not exist(path) + expect(File).not_to exist(path) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end @@ -139,7 +139,7 @@ shared_examples_for "a directory resource" do end it "recursively deletes directories" do - File.should_not exist(path) + expect(File).not_to exist(path) end end end diff --git a/spec/support/shared/functional/file_resource.rb b/spec/support/shared/functional/file_resource.rb index 72b72912bd..bcc2a7da25 100644 --- a/spec/support/shared/functional/file_resource.rb +++ b/spec/support/shared/functional/file_resource.rb @@ -48,10 +48,10 @@ end shared_examples_for "a file with the wrong content" do before do # Assert starting state is as expected - File.should exist(path) + expect(File).to exist(path) # Kinda weird, in this case @expected_checksum is the cksum of the file # with incorrect content. - sha256_checksum(path).should == @expected_checksum + expect(sha256_checksum(path)).to eq(@expected_checksum) end describe "when diff is disabled" do @@ -65,20 +65,20 @@ shared_examples_for "a file with the wrong content" do end it "overwrites the file with the updated content when the :create action is run" do - File.stat(path).mtime.should > @expected_mtime - sha256_checksum(path).should_not == @expected_checksum + expect(File.stat(path).mtime).to be > @expected_mtime + expect(sha256_checksum(path)).not_to eq(@expected_checksum) end it "backs up the existing file" do - Dir.glob(backup_glob).size.should equal(1) + expect(Dir.glob(backup_glob).size).to equal(1) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end it "should restore the security contexts on selinux", :selinux_only do - selinux_security_context_restored?(path).should be_true + expect(selinux_security_context_restored?(path)).to be_truthy end end @@ -89,11 +89,11 @@ shared_examples_for "a file with the wrong content" do end it "should not attempt to backup the existing file if :backup == 0" do - Dir.glob(backup_glob).size.should equal(0) + expect(Dir.glob(backup_glob).size).to equal(0) end it "should restore the security contexts on selinux", :selinux_only do - selinux_security_context_restored?(path).should be_true + expect(selinux_security_context_restored?(path)).to be_truthy end end @@ -114,16 +114,16 @@ shared_examples_for "a file with the wrong content" do end it "doesn't overwrite the file when the :create_if_missing action is run" do - File.stat(path).mtime.should == @expected_mtime - sha256_checksum(path).should == @expected_checksum + expect(File.stat(path).mtime).to eq(@expected_mtime) + expect(sha256_checksum(path)).to eq(@expected_checksum) end it "is not marked as updated" do - resource.should_not be_updated_by_last_action + expect(resource).not_to be_updated_by_last_action end it "should restore the security contexts on selinux", :selinux_only do - selinux_security_context_restored?(path).should be_true + expect(selinux_security_context_restored?(path)).to be_truthy end end @@ -133,11 +133,11 @@ shared_examples_for "a file with the wrong content" do end it "deletes the file" do - File.should_not exist(path) + expect(File).not_to exist(path) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end @@ -146,14 +146,14 @@ shared_examples_for "a file with the wrong content" do context "when diff is enabled" do describe 'sensitive attribute' do context "should be insensitive by default" do - it { expect(resource.sensitive).to(be_false) } + it { expect(resource.sensitive).to(be_falsey) } end context "when set" do before { resource.sensitive(true) } it "should be set on the resource" do - expect(resource.sensitive).to(be_true) + expect(resource.sensitive).to(be_truthy) end context "when running :create action" do @@ -181,8 +181,8 @@ end shared_examples_for "a file with the correct content" do before do # Assert starting state is as expected - File.should exist(path) - sha256_checksum(path).should == @expected_checksum + expect(File).to exist(path) + expect(sha256_checksum(path)).to eq(@expected_checksum) end include_context "diff disabled" @@ -192,19 +192,19 @@ shared_examples_for "a file with the correct content" do resource.run_action(:create) end it "does not overwrite the original when the :create action is run" do - sha256_checksum(path).should == @expected_checksum + expect(sha256_checksum(path)).to eq(@expected_checksum) end it "does not update the mtime of the file when the :create action is run" do - File.stat(path).mtime.should == @expected_mtime + expect(File.stat(path).mtime).to eq(@expected_mtime) end it "is not marked as updated by last action" do - resource.should_not be_updated_by_last_action + expect(resource).not_to be_updated_by_last_action end it "should restore the security contexts on selinux", :selinux_only do - selinux_security_context_restored?(path).should be_true + expect(selinux_security_context_restored?(path)).to be_truthy end end @@ -214,15 +214,15 @@ shared_examples_for "a file with the correct content" do end it "doesn't overwrite the file when the :create_if_missing action is run" do - sha256_checksum(path).should == @expected_checksum + expect(sha256_checksum(path)).to eq(@expected_checksum) end it "is not marked as updated by last action" do - resource.should_not be_updated_by_last_action + expect(resource).not_to be_updated_by_last_action end it "should restore the security contexts on selinux", :selinux_only do - selinux_security_context_restored?(path).should be_true + expect(selinux_security_context_restored?(path)).to be_truthy end end @@ -232,11 +232,11 @@ shared_examples_for "a file with the correct content" do end it "deletes the file when the :delete action is run" do - File.should_not exist(path) + expect(File).not_to exist(path) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end end @@ -300,7 +300,7 @@ shared_examples_for "a file resource" do it "successfully doesn't create the file" do resource.run_action(:create) # should not raise - File.should_not exist(path) + expect(File).not_to exist(path) end end @@ -308,14 +308,14 @@ shared_examples_for "a file resource" do describe "when setting atomic_update" do it "booleans should work" do - lambda {resource.atomic_update(true)}.should_not raise_error - lambda {resource.atomic_update(false)}.should_not raise_error + expect {resource.atomic_update(true)}.not_to raise_error + expect {resource.atomic_update(false)}.not_to raise_error end it "anything else should raise an error" do - lambda {resource.atomic_update(:copy)}.should raise_error(ArgumentError) - lambda {resource.atomic_update(:move)}.should raise_error(ArgumentError) - lambda {resource.atomic_update(958)}.should raise_error(ArgumentError) + expect {resource.atomic_update(:copy)}.to raise_error(ArgumentError) + expect {resource.atomic_update(:move)}.to raise_error(ArgumentError) + expect {resource.atomic_update(958)}.to raise_error(ArgumentError) end end @@ -340,24 +340,24 @@ shared_examples_for "file resource not pointing to a real file" do describe "when force_unlink is set to true" do it ":create unlinks the target" do - real_file?(path).should be_false + expect(real_file?(path)).to be_falsey resource.force_unlink(true) resource.run_action(:create) - real_file?(path).should be_true - binread(path).should == expected_content - resource.should be_updated_by_last_action + expect(real_file?(path)).to be_truthy + expect(binread(path)).to eq(expected_content) + expect(resource).to be_updated_by_last_action end end describe "when force_unlink is set to false" do it ":create raises an error" do - lambda {resource.run_action(:create) }.should raise_error(Chef::Exceptions::FileTypeMismatch) + expect {resource.run_action(:create) }.to raise_error(Chef::Exceptions::FileTypeMismatch) end end describe "when force_unlink is not set (default)" do it ":create raises an error" do - lambda {resource.run_action(:create) }.should raise_error(Chef::Exceptions::FileTypeMismatch) + expect {resource.run_action(:create) }.to raise_error(Chef::Exceptions::FileTypeMismatch) end end end @@ -441,7 +441,7 @@ shared_examples_for "a configured file resource" do after(:each) do # symlink should never be followed - binread(symlink_target).should == "This is so wrong!!!" + expect(binread(symlink_target)).to eq("This is so wrong!!!") end it_behaves_like "file resource not pointing to a real file" @@ -477,7 +477,7 @@ shared_examples_for "a configured file resource" do end it "raises an InvalidSymlink error" do - lambda { resource.run_action(:create) }.should raise_error(Chef::Exceptions::InvalidSymlink) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::InvalidSymlink) end it "issues a warning/assumption in whyrun mode" do @@ -505,7 +505,7 @@ shared_examples_for "a configured file resource" do FileUtils.rm_rf(link_path) end it "raises an InvalidSymlink error" do - lambda { resource.run_action(:create) }.should raise_error(Chef::Exceptions::InvalidSymlink) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::InvalidSymlink) end it "issues a warning/assumption in whyrun mode" do @@ -536,7 +536,7 @@ shared_examples_for "a configured file resource" do end it "raises an InvalidSymlink error" do - lambda { resource.run_action(:create) }.should raise_error(Chef::Exceptions::FileTypeMismatch) + expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::FileTypeMismatch) end it "issues a warning/assumption in whyrun mode" do @@ -564,7 +564,7 @@ shared_examples_for "a configured file resource" do after(:each) do # shared examples should not change our test setup of a file resource # pointing at a symlink: - resource.path.should == link_path + expect(resource.path).to eq(link_path) FileUtils.rm_rf(link_path) end @@ -581,7 +581,7 @@ shared_examples_for "a configured file resource" do it "does not replace the symlink with a real file" do resource.run_action(:create) - File.should be_symlink(link_path) + expect(File).to be_symlink(link_path) end end @@ -593,17 +593,17 @@ shared_examples_for "a configured file resource" do end it "updates the source file content" do - pending + skip end it "marks the resource as updated" do resource.run_action(:create) - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end it "does not replace the symlink with a real file" do resource.run_action(:create) - File.should be_symlink(link_path) + expect(File).to be_symlink(link_path) end end @@ -646,15 +646,15 @@ shared_examples_for "a configured file resource" do after(:each) do # shared examples should not change our test setup of a file resource # pointing at a symlink: - resource.path.should == link_to_link_path + expect(resource.path).to eq(link_to_link_path) FileUtils.rm_rf(link_to_file_path) FileUtils.rm_rf(link_to_link_path) end it "does not replace the symlink with a real file" do resource.run_action(:create) - File.should be_symlink(link_to_link_path) - File.should be_symlink(link_to_file_path) + expect(File).to be_symlink(link_to_link_path) + expect(File).to be_symlink(link_to_file_path) end end @@ -686,9 +686,9 @@ shared_examples_for "a configured file resource" do it ":create updates the target" do resource.force_unlink(true) resource.run_action(:create) - real_file?(path).should be_true - binread(path).should == expected_content - resource.should be_updated_by_last_action + expect(real_file?(path)).to be_truthy + expect(binread(path)).to eq(expected_content) + expect(resource).to be_updated_by_last_action end end @@ -696,9 +696,9 @@ shared_examples_for "a configured file resource" do it ":create updates the target" do resource.force_unlink(true) resource.run_action(:create) - real_file?(path).should be_true - binread(path).should == expected_content - resource.should be_updated_by_last_action + expect(real_file?(path)).to be_truthy + expect(binread(path)).to eq(expected_content) + expect(resource).to be_updated_by_last_action end end @@ -706,9 +706,9 @@ shared_examples_for "a configured file resource" do it ":create updates the target" do resource.force_unlink(true) resource.run_action(:create) - real_file?(path).should be_true - binread(path).should == expected_content - resource.should be_updated_by_last_action + expect(real_file?(path)).to be_truthy + expect(binread(path)).to eq(expected_content) + expect(resource).to be_updated_by_last_action end end end @@ -800,7 +800,7 @@ shared_examples_for "a configured file resource" do end before(:each) do - path.bytesize.should <= 104 + expect(path.bytesize).to be <= 104 UNIXServer.new(path) end @@ -821,8 +821,8 @@ shared_examples_for "a configured file resource" do end it "should notify the other resources correctly" do - resource.should be_updated_by_last_action - resource.run_context.immediate_notifications(resource).length.should == 1 + expect(resource).to be_updated_by_last_action + expect(resource.run_context.immediate_notifications(resource).length).to eq(1) end end @@ -838,8 +838,8 @@ shared_examples_for "a configured file resource" do end it "should notify the other resources correctly" do - resource.should be_updated_by_last_action - resource.run_context.immediate_notifications(resource).length.should == 1 + expect(resource).to be_updated_by_last_action + expect(resource.run_context.immediate_notifications(resource).length).to eq(1) end end end @@ -847,7 +847,7 @@ shared_examples_for "a configured file resource" do context "when the target file does not exist" do before do # Assert starting state is expected - File.should_not exist(path) + expect(File).not_to exist(path) end describe "when running action :create" do @@ -856,19 +856,19 @@ shared_examples_for "a configured file resource" do end it "creates the file when the :create action is run" do - File.should exist(path) + expect(File).to exist(path) end it "creates the file with the correct content when the :create action is run" do - binread(path).should == expected_content + expect(binread(path)).to eq(expected_content) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end it "should restore the security contexts on selinux", :selinux_only do - selinux_security_context_restored?(path).should be_true + expect(selinux_security_context_restored?(path)).to be_truthy end end @@ -878,15 +878,15 @@ shared_examples_for "a configured file resource" do end it "creates the file with the correct content" do - binread(path).should == expected_content + expect(binread(path)).to eq(expected_content) end it "is marked as updated by last action" do - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end it "should restore the security contexts on selinux", :selinux_only do - selinux_security_context_restored?(path).should be_true + expect(selinux_security_context_restored?(path)).to be_truthy end end @@ -896,11 +896,11 @@ shared_examples_for "a configured file resource" do end it "deletes the file when the :delete action is run" do - File.should_not exist(path) + expect(File).not_to exist(path) end it "is not marked updated by last action" do - resource.should_not be_updated_by_last_action + expect(resource).not_to be_updated_by_last_action end end end @@ -1001,21 +1001,21 @@ shared_examples_for "a configured file resource" do describe ":create action should run without any updates" do before do # Assert starting state is as expected - File.should exist(path) - sha256_checksum(path).should == @expected_checksum + expect(File).to exist(path) + expect(sha256_checksum(path)).to eq(@expected_checksum) resource.run_action(:create) end it "does not overwrite the original when the :create action is run" do - sha256_checksum(path).should == @expected_checksum + expect(sha256_checksum(path)).to eq(@expected_checksum) end it "does not update the mtime of the file when the :create action is run" do - File.stat(path).mtime.should == @expected_mtime + expect(File.stat(path).mtime).to eq(@expected_mtime) end it "is not marked as updated by last action" do - resource.should_not be_updated_by_last_action + expect(resource).not_to be_updated_by_last_action end end end diff --git a/spec/support/shared/functional/securable_resource.rb b/spec/support/shared/functional/securable_resource.rb index 9999146dee..e016bb685d 100644 --- a/spec/support/shared/functional/securable_resource.rb +++ b/spec/support/shared/functional/securable_resource.rb @@ -163,8 +163,8 @@ shared_examples_for "a securable resource with existing target" do let(:desired_gid) { 1337 } let(:expected_gid) { 1337 } - pending "should set an owner (Rerun specs under root)", :requires_unprivileged_user => true - pending "should set a group (Rerun specs under root)", :requires_unprivileged_user => true + skip "should set an owner (Rerun specs under root)", :requires_unprivileged_user => true + skip "should set a group (Rerun specs under root)", :requires_unprivileged_user => true describe "when setting the owner", :requires_root do before do @@ -173,11 +173,11 @@ shared_examples_for "a securable resource with existing target" do end it "should set an owner" do - File.lstat(path).uid.should == expected_uid + expect(File.lstat(path).uid).to eq(expected_uid) end it "is marked as updated only if changes are made" do - resource.updated_by_last_action?.should == expect_updated? + expect(resource.updated_by_last_action?).to eq(expect_updated?) end end @@ -189,11 +189,11 @@ shared_examples_for "a securable resource with existing target" do end it "should set a group" do - File.lstat(path).gid.should == expected_gid + expect(File.lstat(path).gid).to eq(expected_gid) end it "is marked as updated only if changes are made" do - resource.updated_by_last_action?.should == expect_updated? + expect(resource.updated_by_last_action?).to eq(expect_updated?) end end @@ -206,13 +206,12 @@ shared_examples_for "a securable resource with existing target" do end it "should set permissions as specified" do - pending('Linux does not support lchmod', :if => resource.instance_of?(Chef::Resource::Link) && !os_x? && !freebsd?) do - (File.lstat(path).mode & 007777).should == (@mode_string.oct & 007777) - end + pending("Linux does not support lchmod") + expect{ File.lstat(path).mode & 007777 }.to eq(@mode_string.oct & 007777) end it "is marked as updated only if changes are made" do - resource.updated_by_last_action?.should == expect_updated? + expect(resource.updated_by_last_action?).to eq(expect_updated?) end end @@ -224,13 +223,12 @@ shared_examples_for "a securable resource with existing target" do end it "should set permissions in numeric form as a ruby-interpreted octal" do - pending('Linux does not support lchmod', :if => resource.instance_of?(Chef::Resource::Link) && !os_x? && !freebsd?) do - (File.lstat(path).mode & 007777).should == (@mode_integer & 007777) - end + pending('Linux does not support lchmod') + expect{ File.lstat(path).mode & 007777 }.to eq(@mode_integer & 007777) end it "is marked as updated only if changes are made" do - resource.updated_by_last_action?.should == expect_updated? + expect(resource.updated_by_last_action?).to eq(expect_updated?) end end end @@ -245,11 +243,11 @@ shared_examples_for "a securable resource with existing target" do end it "should set the owner" do - descriptor.owner.should == SID.Administrator + expect(descriptor.owner).to eq(SID.Administrator) end it "is marked as updated only if changes are made" do - resource.updated_by_last_action?.should == expect_updated? + expect(resource.updated_by_last_action?).to eq(expect_updated?) end end @@ -260,11 +258,11 @@ shared_examples_for "a securable resource with existing target" do end it "should set the group" do - descriptor.group.should == SID.Administrators + expect(descriptor.group).to eq(SID.Administrators) end it "is marked as updated only if changes are made" do - resource.updated_by_last_action?.should == expect_updated? + expect(resource.updated_by_last_action?).to eq(expect_updated?) end end @@ -276,11 +274,11 @@ shared_examples_for "a securable resource with existing target" do end it "should set the rights and deny_rights" do - explicit_aces.should == denied_acl(SID.Guest, expected_modify_perms) + allowed_acl(SID.Guest, expected_read_perms) + expect(explicit_aces).to eq(denied_acl(SID.Guest, expected_modify_perms) + allowed_acl(SID.Guest, expected_read_perms)) end it "is marked as updated only if changes are made" do - resource.updated_by_last_action?.should == expect_updated? + expect(resource.updated_by_last_action?).to eq(expect_updated?) end end end @@ -291,81 +289,80 @@ shared_examples_for "a securable resource without existing target" do include_context "diff disabled" context "on Unix", :unix_only do - pending "if we need any securable resource tests on Unix without existing target resource." + skip "if we need any securable resource tests on Unix without existing target resource." end context "on Windows", :windows_only do include_context "use Windows permissions" it "sets owner to Administrators on create if owner is not specified" do - File.exist?(path).should == false + expect(File.exist?(path)).to eq(false) resource.run_action(:create) - descriptor.owner.should == SID.Administrators + expect(descriptor.owner).to eq(SID.Administrators) end it "sets owner when owner is specified" do resource.owner 'Guest' resource.run_action(:create) - descriptor.owner.should == SID.Guest + expect(descriptor.owner).to eq(SID.Guest) end it "fails to set owner when owner has invalid characters" do - lambda { resource.owner 'Lance "The Nose" Glindenberry III' }.should raise_error#(Chef::Exceptions::ValidationFailed) + expect { resource.owner 'Lance "The Nose" Glindenberry III' }.to raise_error#(Chef::Exceptions::ValidationFailed) end it "sets owner when owner is specified with a \\" do resource.owner "#{ENV['USERDOMAIN']}\\Guest" resource.run_action(:create) - descriptor.owner.should == SID.Guest + expect(descriptor.owner).to eq(SID.Guest) end it "leaves owner alone if owner is not specified and resource already exists" do # Set owner to Guest so it's not the same as the current user (which is the default on create) resource.owner 'Guest' resource.run_action(:create) - descriptor.owner.should == SID.Guest + expect(descriptor.owner).to eq(SID.Guest) new_resource = create_resource - new_resource.owner.should == nil + expect(new_resource.owner).to eq(nil) new_resource.run_action(:create) - descriptor.owner.should == SID.Guest + expect(descriptor.owner).to eq(SID.Guest) end it "sets group to None on create if group is not specified" do - resource.group.should == nil - File.exist?(path).should == false + expect(resource.group).to eq(nil) + expect(File.exist?(path)).to eq(false) resource.run_action(:create) - descriptor.group.should == SID.None + expect(descriptor.group).to eq(SID.None) end it "sets group when group is specified" do resource.group 'Everyone' resource.run_action(:create) - descriptor.group.should == SID.Everyone + expect(descriptor.group).to eq(SID.Everyone) end it "fails to set group when group has invalid characters" do - lambda { resource.group 'Lance "The Nose" Glindenberry III' }.should raise_error(Chef::Exceptions::ValidationFailed) + expect { resource.group 'Lance "The Nose" Glindenberry III' }.to raise_error(Chef::Exceptions::ValidationFailed) end it "sets group when group is specified with a \\" do - pending "Need to find a group containing a backslash that is on most peoples' machines" do - resource.group "#{ENV['COMPUTERNAME']}\\Administrators" - resource.run_action(:create) - descriptor.group.should == SID.Everyone - end + pending("Need to find a group containing a backslash that is on most peoples' machines") + resource.group "#{ENV['COMPUTERNAME']}\\Administrators" + resource.run_action(:create) + expect{ descriptor.group }.to eq(SID.Everyone) end it "leaves group alone if group is not specified and resource already exists" do # Set group to Everyone so it's not the default (None) resource.group 'Everyone' resource.run_action(:create) - descriptor.group.should == SID.Everyone + expect(descriptor.group).to eq(SID.Everyone) new_resource = create_resource - new_resource.group.should == nil + expect(new_resource.group).to eq(nil) new_resource.run_action(:create) - descriptor.group.should == SID.Everyone + expect(descriptor.group).to eq(SID.Everyone) end describe "with rights and deny_rights attributes" do @@ -373,38 +370,38 @@ shared_examples_for "a securable resource without existing target" do it "correctly sets :read rights" do resource.rights(:read, 'Guest') resource.run_action(:create) - explicit_aces.should == allowed_acl(SID.Guest, expected_read_perms) + expect(explicit_aces).to eq(allowed_acl(SID.Guest, expected_read_perms)) end it "correctly sets :read_execute rights" do resource.rights(:read_execute, 'Guest') resource.run_action(:create) - explicit_aces.should == allowed_acl(SID.Guest, expected_read_execute_perms) + expect(explicit_aces).to eq(allowed_acl(SID.Guest, expected_read_execute_perms)) end it "correctly sets :write rights" do resource.rights(:write, 'Guest') resource.run_action(:create) - explicit_aces.should == allowed_acl(SID.Guest, expected_write_perms) + expect(explicit_aces).to eq(allowed_acl(SID.Guest, expected_write_perms)) end it "correctly sets :modify rights" do resource.rights(:modify, 'Guest') resource.run_action(:create) - explicit_aces.should == allowed_acl(SID.Guest, expected_modify_perms) + expect(explicit_aces).to eq(allowed_acl(SID.Guest, expected_modify_perms)) end it "correctly sets :full_control rights" do resource.rights(:full_control, 'Guest') resource.run_action(:create) - explicit_aces.should == allowed_acl(SID.Guest, expected_full_control_perms) + expect(explicit_aces).to eq(allowed_acl(SID.Guest, expected_full_control_perms)) end it "correctly sets deny_rights" do # deny is an ACE with full rights, but is a deny type ace, not an allow type resource.deny_rights(:full_control, 'Guest') resource.run_action(:create) - explicit_aces.should == denied_acl(SID.Guest, expected_full_control_perms) + expect(explicit_aces).to eq(denied_acl(SID.Guest, expected_full_control_perms)) end it "Sets multiple rights" do @@ -412,9 +409,10 @@ shared_examples_for "a securable resource without existing target" do resource.rights(:modify, 'Guest') resource.run_action(:create) - explicit_aces.should == + expect(explicit_aces).to eq( allowed_acl(SID.Everyone, expected_read_perms) + allowed_acl(SID.Guest, expected_modify_perms) + ) end it "Sets deny_rights ahead of rights" do @@ -422,9 +420,10 @@ shared_examples_for "a securable resource without existing target" do resource.deny_rights(:modify, 'Guest') resource.run_action(:create) - explicit_aces.should == + expect(explicit_aces).to eq( denied_acl(SID.Guest, expected_modify_perms) + allowed_acl(SID.Everyone, expected_read_perms) + ) end it "Sets deny_rights ahead of rights when specified in reverse order" do @@ -432,9 +431,10 @@ shared_examples_for "a securable resource without existing target" do resource.rights(:read, 'Everyone') resource.run_action(:create) - explicit_aces.should == + expect(explicit_aces).to eq( denied_acl(SID.Guest, expected_modify_perms) + allowed_acl(SID.Everyone, expected_read_perms) + ) end end @@ -452,7 +452,7 @@ shared_examples_for "a securable resource without existing target" do resource.group 'Everyone' resource.run_action(:create) - explicit_aces.should == [ ACE.access_allowed(SID.Guest, Security::FILE_GENERIC_READ) ] + expect(explicit_aces).to eq([ ACE.access_allowed(SID.Guest, Security::FILE_GENERIC_READ) ]) end it "respects mode in numeric form as a ruby-interpreted octal" do @@ -460,7 +460,7 @@ shared_examples_for "a securable resource without existing target" do resource.owner 'Guest' resource.run_action(:create) - explicit_aces.should == [ ACE.access_allowed(SID.Guest, Security::FILE_GENERIC_READ | Security::FILE_GENERIC_WRITE | Security::FILE_GENERIC_EXECUTE | Security::DELETE) ] + expect(explicit_aces).to eq([ ACE.access_allowed(SID.Guest, Security::FILE_GENERIC_READ | Security::FILE_GENERIC_WRITE | Security::FILE_GENERIC_EXECUTE | Security::DELETE) ]) end it "respects the owner, group and everyone bits of mode" do @@ -469,11 +469,11 @@ shared_examples_for "a securable resource without existing target" do resource.group 'Administrators' resource.run_action(:create) - explicit_aces.should == [ + expect(explicit_aces).to eq([ ACE.access_allowed(SID.Guest, Security::FILE_GENERIC_READ | Security::FILE_GENERIC_WRITE | Security::FILE_GENERIC_EXECUTE | Security::DELETE), ACE.access_allowed(SID.Administrators, Security::FILE_GENERIC_READ | Security::FILE_GENERIC_EXECUTE), ACE.access_allowed(SID.Everyone, Security::FILE_GENERIC_READ) - ] + ]) end it "respects the individual read, write and execute bits of mode" do @@ -482,31 +482,31 @@ shared_examples_for "a securable resource without existing target" do resource.group 'Administrators' resource.run_action(:create) - explicit_aces.should == [ + expect(explicit_aces).to eq([ ACE.access_allowed(SID.Guest, Security::FILE_GENERIC_READ), ACE.access_allowed(SID.Administrators, Security::FILE_GENERIC_WRITE | Security::DELETE), ACE.access_allowed(SID.Everyone, Security::FILE_GENERIC_EXECUTE) - ] + ]) end it 'warns when mode tries to set owner bits but owner is not specified' do @warn = [] - Chef::Log.stub(:warn) { |msg| @warn << msg } + allow(Chef::Log).to receive(:warn) { |msg| @warn << msg } resource.mode 0400 resource.run_action(:create) - @warn.include?("Mode 400 includes bits for the owner, but owner is not specified").should be_true + expect(@warn.include?("Mode 400 includes bits for the owner, but owner is not specified")).to be_truthy end it 'warns when mode tries to set group bits but group is not specified' do @warn = [] - Chef::Log.stub(:warn) { |msg| @warn << msg } + allow(Chef::Log).to receive(:warn) { |msg| @warn << msg } resource.mode 0040 resource.run_action(:create) - @warn.include?("Mode 040 includes bits for the group, but group is not specified").should be_true + expect(@warn.include?("Mode 040 includes bits for the group, but group is not specified")).to be_truthy end end @@ -518,12 +518,12 @@ shared_examples_for "a securable resource without existing target" do resource.run_action(:create) descriptor.dacl.each do | ace | - ace.inherited?.should == false + expect(ace.inherited?).to eq(false) end end it "has the inheritable acls of parent directory if no acl is specified" do - File.exist?(path).should == false + expect(File.exist?(path)).to eq(false) # Collect the inheritable acls form the parent by creating a file without # any specific ACLs @@ -542,7 +542,7 @@ shared_examples_for "a securable resource without existing target" do ace.inherited? end - resource_inherited_acls.should == parent_inherited_acls + expect(resource_inherited_acls).to eq(parent_inherited_acls) end end diff --git a/spec/support/shared/functional/securable_resource_with_reporting.rb b/spec/support/shared/functional/securable_resource_with_reporting.rb index b02137a06c..8a2ceed837 100644 --- a/spec/support/shared/functional/securable_resource_with_reporting.rb +++ b/spec/support/shared/functional/securable_resource_with_reporting.rb @@ -56,18 +56,18 @@ shared_examples_for "a securable resource with reporting" do end it "has empty values for file metadata in 'current_resource'" do - current_resource.owner.should be_nil - current_resource.group.should be_nil - current_resource.mode.should be_nil + expect(current_resource.owner).to be_nil + expect(current_resource.group).to be_nil + expect(current_resource.mode).to be_nil end context "and no security metadata is specified in new_resource" do it "sets the metadata values on the new_resource as strings after creating" do resource.run_action(:create) # TODO: most stable way to specify? - resource.owner.should == Etc.getpwuid(Process.uid).name - resource.group.should == @expected_group_name - resource.mode.should == "0#{default_mode}" + expect(resource.owner).to eq(Etc.getpwuid(Process.uid).name) + expect(resource.group).to eq(@expected_group_name) + expect(resource.mode).to eq("0#{default_mode}") end end @@ -87,7 +87,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the owner on new_resource to the username (String) of the desired owner" do - resource.owner.should == expected_user_name + expect(resource.owner).to eq(expected_user_name) end end @@ -110,7 +110,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the owner on new_resource to the uid (Integer) of the desired owner" do - resource.owner.should == expected_uid + expect(resource.owner).to eq(expected_uid) end end @@ -124,7 +124,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the group on new_resource to the group name (String) of the group" do - resource.group.should == expected_group_name + expect(resource.group).to eq(expected_group_name) end end @@ -138,7 +138,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the group on new_resource to the gid (Integer)" do - resource.group.should == expected_gid + expect(resource.group).to eq(expected_gid) end end @@ -155,7 +155,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets mode on the new_resource as a String" do - resource.mode.should == expected_mode + expect(resource.mode).to eq(expected_mode) end end @@ -169,7 +169,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets mode on the new resource as a String" do - resource.mode.should == expected_mode + expect(resource.mode).to eq(expected_mode) end end end @@ -183,9 +183,9 @@ shared_examples_for "a securable resource with reporting" do context "and no security metadata is specified in new_resource" do it "sets the current values on current resource as strings" do # TODO: most stable way to specify? - current_resource.owner.should == Etc.getpwuid(Process.uid).name - current_resource.group.should == @expected_group_name - current_resource.mode.should == "0#{((0100666 - File.umask) & 07777).to_s(8)}" + expect(current_resource.owner).to eq(Etc.getpwuid(Process.uid).name) + expect(current_resource.group).to eq(@expected_group_name) + expect(current_resource.mode).to eq("0#{((0100666 - File.umask) & 07777).to_s(8)}") end end @@ -198,7 +198,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the owner on new_resource to the username (String) of the desired owner" do - current_resource.owner.should == expected_user_name + expect(current_resource.owner).to eq(expected_user_name) end end @@ -212,7 +212,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the owner on new_resource to the uid (Integer) of the desired owner" do - current_resource.owner.should == expected_uid + expect(current_resource.owner).to eq(expected_uid) end end @@ -222,7 +222,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the group on new_resource to the group name (String) of the group" do - current_resource.group.should == @expected_group_name + expect(current_resource.group).to eq(@expected_group_name) end end @@ -233,7 +233,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the group on new_resource to the gid (Integer)" do - current_resource.group.should == @expected_gid + expect(current_resource.group).to eq(@expected_gid) end end @@ -247,7 +247,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets mode on the new_resource as a String" do - current_resource.mode.should == expected_mode + expect(current_resource.mode).to eq(expected_mode) end end @@ -260,7 +260,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets mode on the new resource as a String" do - current_resource.mode.should == expected_mode + expect(current_resource.mode).to eq(expected_mode) end end end @@ -268,11 +268,6 @@ shared_examples_for "a securable resource with reporting" do describe "reading file security metadata for reporting on windows", :windows_only do - before do - pending "windows reporting not yet fully supported" - end - - context "when the target file doesn't exist" do # Windows reporting data should look like this (+/- ish): @@ -284,23 +279,28 @@ shared_examples_for "a securable resource with reporting" do end it "has empty values for file metadata in 'current_resource'" do - current_resource.owner.should be_nil - current_resource.expanded_rights.should be_nil + pending "windows reporting not yet fully supported" + expect(current_resource.owner).to be_nil + expect(current_resource.expanded_rights).to be_nil end context "and no security metadata is specified in new_resource" do + before do + pending "windows reporting not yet fully supported" + end + it "sets the metadata values on the new_resource as strings after creating" do resource.run_action(:create) # TODO: most stable way to specify? - resource.owner.should == etc.getpwuid(process.uid).name - resource.state[:expanded_rights].should == { "CURRENTUSER" => { "permissions" => ALL_EXPANDED_PERMISSIONS, "flags" => [] }} - resource.state[:expanded_deny_rights].should == {} - resource.state[:inherits].should be_true + expect(resource.owner).to eq(etc.getpwuid(process.uid).name) + expect(resource.state[:expanded_rights]).to eq({ "CURRENTUSER" => { "permissions" => ALL_EXPANDED_PERMISSIONS, "flags" => [] }}) + expect(resource.state[:expanded_deny_rights]).to eq({}) + expect(resource.state[:inherits]).to be_truthy end end - context "and owner is specified with a string (username) in new_resource" do + context "and owner is specified with a string (username) in new_resource" do # TODO/bug: duplicated from the "securable resource" tests let(:expected_user_name) { 'Guest' } @@ -311,7 +311,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the owner on new_resource to the username (string) of the desired owner" do - resource.owner.should == expected_user_name + expect(resource.owner).to eq(expected_user_name) end end @@ -322,12 +322,13 @@ shared_examples_for "a securable resource with reporting" do let(:expected_user_name) { 'domain\user' } before do + pending "windows reporting not yet fully supported" resource.owner(expected_user_name) resource.run_action(:create) end it "sets the owner on new_resource to the fully qualified name of the desired owner" do - resource.owner.should == expected_user_name + expect(resource.owner).to eq(expected_user_name) end end @@ -335,6 +336,7 @@ shared_examples_for "a securable resource with reporting" do context "when the target file exists" do before do + pending "windows reporting not yet fully supported" FileUtils.touch(resource.path) resource.action(:create) end @@ -342,8 +344,8 @@ shared_examples_for "a securable resource with reporting" do context "and no security metadata is specified in new_resource" do it "sets the current values on current resource as strings" do # TODO: most stable way to specify? - current_resource.owner.should == etc.getpwuid(process.uid).name - current_resource.expanded_rights.should == { "CURRENTUSER" => ALL_EXPANDED_PERMISSIONS } + expect(current_resource.owner).to eq(etc.getpwuid(process.uid).name) + expect(current_resource.expanded_rights).to eq({ "CURRENTUSER" => ALL_EXPANDED_PERMISSIONS }) end end @@ -356,7 +358,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the owner on current_resource to the username (string) of the desired owner" do - current_resource.owner.should == expected_user_name + expect(current_resource.owner).to eq(expected_user_name) end end @@ -370,7 +372,7 @@ shared_examples_for "a securable resource with reporting" do end it "sets the owner on current_resource to the fully qualified name of the desired owner" do - current_resource.owner.should == expected_uid + expect(current_resource.owner).to eq(expected_uid) end end @@ -378,7 +380,7 @@ shared_examples_for "a securable resource with reporting" do # TODO: before do blah it "sets the expanded_rights on the current resource" do - pending + skip end end @@ -386,7 +388,7 @@ shared_examples_for "a securable resource with reporting" do # TODO: before do blah it "sets the expanded rights on the current resource" do - pending + skip end end diff --git a/spec/support/shared/functional/windows_script.rb b/spec/support/shared/functional/windows_script.rb index 866caf4b20..35b86dc4e8 100644 --- a/spec/support/shared/functional/windows_script.rb +++ b/spec/support/shared/functional/windows_script.rb @@ -83,29 +83,29 @@ shared_context Chef::Resource::WindowsScript do it "should create a process with the expected architecture" do resource.run_action(:run) - get_process_architecture.should == expected_architecture_output.downcase + expect(get_process_architecture).to eq(expected_architecture_output.downcase) end it "should execute guards with the same architecture as the resource" do resource.only_if resource_guard_command resource.run_action(:run) - get_process_architecture.should == expected_architecture_output.downcase - get_guard_process_architecture.should == expected_architecture_output.downcase - get_guard_process_architecture.should == get_process_architecture + expect(get_process_architecture).to eq(expected_architecture_output.downcase) + expect(get_guard_process_architecture).to eq(expected_architecture_output.downcase) + expect(get_guard_process_architecture).to eq(get_process_architecture) end let (:architecture) { :x86_64 } it "should execute a 64-bit guard if the guard's architecture is specified as 64-bit", :windows64_only do resource.only_if resource_guard_command, :architecture => :x86_64 resource.run_action(:run) - get_guard_process_architecture.should == 'amd64' + expect(get_guard_process_architecture).to eq('amd64') end let (:architecture) { :i386 } it "should execute a 32-bit guard if the guard's architecture is specified as 32-bit" do resource.only_if resource_guard_command, :architecture => :i386 resource.run_action(:run) - get_guard_process_architecture.should == 'x86' + expect(get_guard_process_architecture).to eq('x86') end end end @@ -122,11 +122,11 @@ shared_context Chef::Resource::WindowsScript do context "when evaluating guards" do it "has a guard_interpreter attribute set to the short name of the resource" do - resource.guard_interpreter.should == resource.resource_name + expect(resource.guard_interpreter).to eq(resource.resource_name) resource.not_if "findstr.exe /thiscommandhasnonzeroexitstatus" expect(Chef::Resource).to receive(:resource_for_node).and_call_original expect(resource.class).to receive(:new).and_call_original - resource.should_skip?(:run).should be_false + expect(resource.should_skip?(:run)).to be_falsey end end diff --git a/spec/support/shared/integration/knife_support.rb b/spec/support/shared/integration/knife_support.rb index fd12998152..30293be6cf 100644 --- a/spec/support/shared/integration/knife_support.rb +++ b/spec/support/shared/integration/knife_support.rb @@ -103,6 +103,9 @@ module KnifeSupport private class KnifeResult + + include ::RSpec::Matchers + def initialize(stdout, stderr, exit_code) @stdout = stdout @stderr = stderr @@ -150,20 +153,20 @@ module KnifeSupport stderr_actual = @stderr.sub(/^WARNING: No knife configuration file found\n/, '') if expected[:stderr].is_a?(Regexp) - stderr_actual.should =~ expected[:stderr] + expect(stderr_actual).to match(expected[:stderr]) else - stderr_actual.should == expected[:stderr] + expect(stderr_actual).to eq(expected[:stderr]) end stdout_actual = @stdout if Chef::Platform.windows? stderr_actual = stderr_actual.gsub("\r\n", "\n") stdout_actual = stdout_actual.gsub("\r\n", "\n") end - @exit_code.should == expected[:exit_code] + expect(@exit_code).to eq(expected[:exit_code]) if expected[:stdout].is_a?(Regexp) - stdout_actual.should =~ expected[:stdout] + expect(stdout_actual).to match(expected[:stdout]) else - stdout_actual.should == expected[:stdout] + expect(stdout_actual).to eq(expected[:stdout]) end end end diff --git a/spec/support/shared/matchers/exit_with_code.rb b/spec/support/shared/matchers/exit_with_code.rb index 957586c85d..32ebf8db15 100644 --- a/spec/support/shared/matchers/exit_with_code.rb +++ b/spec/support/shared/matchers/exit_with_code.rb @@ -12,12 +12,12 @@ RSpec::Matchers.define :exit_with_code do |exp_code| actual and actual == exp_code end - failure_message_for_should do |block| + failure_message do |block| "expected block to call exit(#{exp_code}) but exit" + (actual.nil? ? " not called" : "(#{actual}) was called") end - failure_message_for_should_not do |block| + failure_message_when_negated do |block| "expected block not to call exit(#{exp_code})" end @@ -25,4 +25,8 @@ RSpec::Matchers.define :exit_with_code do |exp_code| "expect block to call exit(#{exp_code})" end + def supports_block_expectations? + true + end + end diff --git a/spec/support/shared/unit/api_error_inspector.rb b/spec/support/shared/unit/api_error_inspector.rb index 7577cb6c12..e85fa971e9 100644 --- a/spec/support/shared/unit/api_error_inspector.rb +++ b/spec/support/shared/unit/api_error_inspector.rb @@ -72,7 +72,7 @@ shared_examples_for "an api error inspector" do before do @response_body = "synchronize the clock on your host" @response = Net::HTTPUnauthorized.new("1.1", "401", "(response) unauthorized") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) unauthorized", @response) @inspector = described_class.new(@node_name, @exception, @config) @inspector.add_explanation(@description) @@ -88,7 +88,7 @@ shared_examples_for "an api error inspector" do before do @response_body = "check your key and node name" @response = Net::HTTPUnauthorized.new("1.1", "401", "(response) unauthorized") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) unauthorized", @response) @inspector = described_class.new(@node_name, @exception, @config) @inspector.add_explanation(@description) @@ -104,7 +104,7 @@ shared_examples_for "an api error inspector" do before do @response_body = "forbidden" @response = Net::HTTPForbidden.new("1.1", "403", "(response) forbidden") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) forbidden", @response) @inspector = described_class.new(@node_name, @exception, @config) @inspector.add_explanation(@description) @@ -120,7 +120,7 @@ shared_examples_for "an api error inspector" do before do @response_body = "didn't like your data" @response = Net::HTTPBadRequest.new("1.1", "400", "(response) bad request") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) bad request", @response) @inspector = described_class.new(@node_name, @exception, @config) @inspector.add_explanation(@description) @@ -136,7 +136,7 @@ shared_examples_for "an api error inspector" do before do @response_body = "probably caused by a redirect to a get" @response = Net::HTTPNotFound.new("1.1", "404", "(response) not found") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) not found", @response) @inspector = described_class.new(@node_name, @exception, @config) @inspector.add_explanation(@description) @@ -151,7 +151,7 @@ shared_examples_for "an api error inspector" do before do @response_body = "sad trombone" @response = Net::HTTPInternalServerError.new("1.1", "500", "(response) internal server error") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPFatalError.new("(exception) internal server error", @response) @inspector = described_class.new(@node_name, @exception, @config) @inspector.add_explanation(@description) @@ -166,7 +166,7 @@ shared_examples_for "an api error inspector" do before do @response_body = "sad trombone orchestra" @response = Net::HTTPBadGateway.new("1.1", "502", "(response) bad gateway") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPFatalError.new("(exception) bad gateway", @response) @inspector = described_class.new(@node_name, @exception, @config) @inspector.add_explanation(@description) diff --git a/spec/support/shared/unit/execute_resource.rb b/spec/support/shared/unit/execute_resource.rb index 298e0c5baf..d6fb88db5c 100644 --- a/spec/support/shared/unit/execute_resource.rb +++ b/spec/support/shared/unit/execute_resource.rb @@ -26,79 +26,79 @@ shared_examples_for "an execute resource" do end it "should create a new Chef::Resource::Execute" do - @resource.should be_a_kind_of(Chef::Resource) - @resource.should be_a_kind_of(Chef::Resource::Execute) + expect(@resource).to be_a_kind_of(Chef::Resource) + expect(@resource).to be_a_kind_of(Chef::Resource::Execute) end it "should set the command to the first argument to new" do - @resource.command.should eql(resource_instance_name) + expect(@resource.command).to eql(resource_instance_name) end it "should accept an array on instantiation, too" do resource = Chef::Resource::Execute.new(%w{something else}) - resource.should be_a_kind_of(Chef::Resource) - resource.should be_a_kind_of(Chef::Resource::Execute) - resource.command.should eql(%w{something else}) + expect(resource).to be_a_kind_of(Chef::Resource) + expect(resource).to be_a_kind_of(Chef::Resource::Execute) + expect(resource.command).to eql(%w{something else}) end it "should accept a string for the command to run" do @resource.command "something" - @resource.command.should eql("something") + expect(@resource.command).to eql("something") end it "should accept an array for the command to run" do @resource.command %w{something else} - @resource.command.should eql(%w{something else}) + expect(@resource.command).to eql(%w{something else}) end it "should accept a string for the cwd" do @resource.cwd "something" - @resource.cwd.should eql("something") + expect(@resource.cwd).to eql("something") end it "should accept a hash for the environment" do test_hash = { :one => :two } @resource.environment(test_hash) - @resource.environment.should eql(test_hash) + expect(@resource.environment).to eql(test_hash) end it "allows the environment to be specified with #env" do - @resource.should respond_to(:env) + expect(@resource).to respond_to(:env) end it "should accept a string for the group" do @resource.group "something" - @resource.group.should eql("something") + expect(@resource.group).to eql("something") end it "should accept an integer for the group" do @resource.group 1 - @resource.group.should eql(1) + expect(@resource.group).to eql(1) end it "should accept an integer for the return code" do @resource.returns 1 - @resource.returns.should eql(1) + expect(@resource.returns).to eql(1) end it "should accept an integer for the timeout" do @resource.timeout 1 - @resource.timeout.should eql(1) + expect(@resource.timeout).to eql(1) end it "should accept a string for the user" do @resource.user "something" - @resource.user.should eql("something") + expect(@resource.user).to eql("something") end it "should accept an integer for the user" do @resource.user 1 - @resource.user.should eql(1) + expect(@resource.user).to eql(1) end it "should accept a string for creates" do @resource.creates "something" - @resource.creates.should eql("something") + expect(@resource.creates).to eql("something") end describe "when it has cwd, environment, group, path, return value, and a user" do @@ -112,7 +112,7 @@ shared_examples_for "an execute resource" do end it "returns the command as its identity" do - @resource.identity.should == "grep" + expect(@resource.identity).to eq("grep") end end end diff --git a/spec/support/shared/unit/file_system_support.rb b/spec/support/shared/unit/file_system_support.rb index 3e771dd187..358f0c405c 100644 --- a/spec/support/shared/unit/file_system_support.rb +++ b/spec/support/shared/unit/file_system_support.rb @@ -56,7 +56,7 @@ module FileSystemSupport def no_blocking_calls_allowed [ Chef::ChefFS::FileSystem::MemoryFile, Chef::ChefFS::FileSystem::MemoryDir ].each do |c| [ :children, :exists?, :read ].each do |m| - c.any_instance.stub(m).and_raise("#{m.to_s} should not be called") + allow_any_instance_of(c).to receive(m).and_raise("#{m.to_s} should not be called") end end end @@ -64,7 +64,7 @@ module FileSystemSupport def list_should_yield_paths(fs, pattern_str, *expected_paths) result_paths = [] Chef::ChefFS::FileSystem.list(fs, pattern(pattern_str)).each { |result| result_paths << result.path } - result_paths.should =~ expected_paths + expect(result_paths).to match_array(expected_paths) end end diff --git a/spec/support/shared/unit/platform_introspector.rb b/spec/support/shared/unit/platform_introspector.rb index f76ddbdf9e..9f42c985f8 100644 --- a/spec/support/shared/unit/platform_introspector.rb +++ b/spec/support/shared/unit/platform_introspector.rb @@ -44,49 +44,49 @@ shared_examples_for "a platform introspector" do it "returns a default value when there is no known platform" do node = Hash.new - platform_introspector.value_for_platform(@platform_hash).should == "default" + expect(platform_introspector.value_for_platform(@platform_hash)).to eq("default") end it "returns a default value when there is no known platform family" do - platform_introspector.value_for_platform_family(@platform_family_hash).should == "default value" + expect(platform_introspector.value_for_platform_family(@platform_family_hash)).to eq("default value") end it "returns a default value when the current platform doesn't match" do node.automatic_attrs[:platform] = "not-a-known-platform" - platform_introspector.value_for_platform(@platform_hash).should == "default" + expect(platform_introspector.value_for_platform(@platform_hash)).to eq("default") end it "returns a default value when current platform_family doesn't match" do node.automatic_attrs[:platform_family] = "ultra-derived-linux" - platform_introspector.value_for_platform_family(@platform_family_hash).should == "default value" + expect(platform_introspector.value_for_platform_family(@platform_family_hash)).to eq("default value") end it "returns a value based on the current platform" do node.automatic_attrs[:platform] = "openbsd" - platform_introspector.value_for_platform(@platform_hash).should == "openbsd" + expect(platform_introspector.value_for_platform(@platform_hash)).to eq("openbsd") end it "returns a value based on the current platform family" do node.automatic_attrs[:platform_family] = "debian" - platform_introspector.value_for_platform_family(@platform_family_hash).should == "debian value" + expect(platform_introspector.value_for_platform_family(@platform_family_hash)).to eq("debian value") end it "returns a version-specific value based on the current platform" do node.automatic_attrs[:platform] = "openbsd" node.automatic_attrs[:platform_version] = "1.2.3" - platform_introspector.value_for_platform(@platform_hash).should == "openbsd-1.2.3" + expect(platform_introspector.value_for_platform(@platform_hash)).to eq("openbsd-1.2.3") end it "returns a value based on the current platform if version not found" do node.automatic_attrs[:platform] = "openbsd" node.automatic_attrs[:platform_version] = "0.0.0" - platform_introspector.value_for_platform(@platform_hash).should == "openbsd" + expect(platform_introspector.value_for_platform(@platform_hash)).to eq("openbsd") end it 'returns the exact match' do node.automatic_attrs[:platform] = 'exact_match' node.automatic_attrs[:platform_version] = '1.2.3' - platform_introspector.value_for_platform(@platform_hash).should == 'exact' + expect(platform_introspector.value_for_platform(@platform_hash)).to eq('exact') end it 'raises RuntimeError' do @@ -98,20 +98,20 @@ shared_examples_for "a platform introspector" do it 'should return the value for that match' do node.automatic_attrs[:platform] = 'successful_matches' node.automatic_attrs[:platform_version] = '2.9' - platform_introspector.value_for_platform(@platform_hash).should == 'matched < 3.0' + expect(platform_introspector.value_for_platform(@platform_hash)).to eq('matched < 3.0') end describe "when platform versions is an array" do it "returns a version-specific value based on the current platform" do node.automatic_attrs[:platform] = "debian" node.automatic_attrs[:platform_version] = "6" - platform_introspector.value_for_platform(@platform_hash).should == "debian-5/6" + expect(platform_introspector.value_for_platform(@platform_hash)).to eq("debian-5/6") end it "returns a value based on the current platform if version not found" do node.automatic_attrs[:platform] = "debian" node.automatic_attrs[:platform_version] = "0.0.0" - platform_introspector.value_for_platform(@platform_hash).should == "debian" + expect(platform_introspector.value_for_platform(@platform_hash)).to eq("debian") end end @@ -119,17 +119,17 @@ shared_examples_for "a platform introspector" do it "returns true if the node is a provided platform and platforms are provided as symbols" do node.automatic_attrs[:platform] = 'ubuntu' - platform_introspector.platform?([:redhat, :ubuntu]).should == true + expect(platform_introspector.platform?([:redhat, :ubuntu])).to eq(true) end it "returns true if the node is a provided platform and platforms are provided as strings" do node.automatic_attrs[:platform] = 'ubuntu' - platform_introspector.platform?(["redhat", "ubuntu"]).should == true + expect(platform_introspector.platform?(["redhat", "ubuntu"])).to eq(true) end it "returns false if the node is not of the provided platforms" do node.automatic_attrs[:platform] = 'ubuntu' - platform_introspector.platform?(:splatlinux).should == false + expect(platform_introspector.platform?(:splatlinux)).to eq(false) end end @@ -137,21 +137,21 @@ shared_examples_for "a platform introspector" do it "returns true if the node is in a provided platform family and families are provided as symbols" do node.automatic_attrs[:platform_family] = 'debian' - platform_introspector.platform_family?([:rhel, :debian]).should == true + expect(platform_introspector.platform_family?([:rhel, :debian])).to eq(true) end it "returns true if the node is a provided platform and platforms are provided as strings" do node.automatic_attrs[:platform_family] = 'rhel' - platform_introspector.platform_family?(["rhel", "debian"]).should == true + expect(platform_introspector.platform_family?(["rhel", "debian"])).to eq(true) end it "returns false if the node is not of the provided platforms" do node.automatic_attrs[:platform_family] = 'suse' - platform_introspector.platform_family?(:splatlinux).should == false + expect(platform_introspector.platform_family?(:splatlinux)).to eq(false) end it "returns false if the node is not of the provided platforms and platform_family is not set" do - platform_introspector.platform_family?(:splatlinux).should == false + expect(platform_introspector.platform_family?(:splatlinux)).to eq(false) end end @@ -170,13 +170,13 @@ shared_examples_for "a platform introspector" do it "returns the correct default for a given platform" do node.automatic_attrs[:platform] = "debian" node.automatic_attrs[:platform_version] = '9000' - platform_introspector.value_for_platform(@platform_hash).should == [ :restart, :reload, :status ] + expect(platform_introspector.value_for_platform(@platform_hash)).to eq([ :restart, :reload, :status ]) end it "returns the correct platform+version specific value " do node.automatic_attrs[:platform] = "debian" node.automatic_attrs[:platform_version] = '4.0' - platform_introspector.value_for_platform(@platform_hash).should == [:restart, :reload] + expect(platform_introspector.value_for_platform(@platform_hash)).to eq([:restart, :reload]) end end diff --git a/spec/support/shared/unit/provider/file.rb b/spec/support/shared/unit/provider/file.rb index 85c8e2fb34..25c2b52b1b 100644 --- a/spec/support/shared/unit/provider/file.rb +++ b/spec/support/shared/unit/provider/file.rb @@ -43,67 +43,67 @@ end # this is all getting a bit stupid, CHEF-4802 cut to remove all this def setup_normal_file [ resource_path, normalized_path, windows_path].each do |path| - File.stub(:file?).with(path).and_return(true) - File.stub(:exists?).with(path).and_return(true) - File.stub(:exist?).with(path).and_return(true) - File.stub(:directory?).with(path).and_return(false) - File.stub(:writable?).with(path).and_return(true) - file_symlink_class.stub(:symlink?).with(path).and_return(false) - File.stub(:realpath?).with(path).and_return(normalized_path) + allow(File).to receive(:file?).with(path).and_return(true) + allow(File).to receive(:exists?).with(path).and_return(true) + allow(File).to receive(:exist?).with(path).and_return(true) + allow(File).to receive(:directory?).with(path).and_return(false) + allow(File).to receive(:writable?).with(path).and_return(true) + allow(file_symlink_class).to receive(:symlink?).with(path).and_return(false) + allow(File).to receive(:realpath?).with(path).and_return(normalized_path) end - File.stub(:directory?).with(enclosing_directory).and_return(true) + allow(File).to receive(:directory?).with(enclosing_directory).and_return(true) end def setup_missing_file [ resource_path, normalized_path, windows_path].each do |path| - File.stub(:file?).with(path).and_return(false) - File.stub(:realpath?).with(path).and_return(resource_path) - File.stub(:exists?).with(path).and_return(false) - File.stub(:exist?).with(path).and_return(false) - File.stub(:directory?).with(path).and_return(false) - File.stub(:writable?).with(path).and_return(false) - file_symlink_class.stub(:symlink?).with(path).and_return(false) + allow(File).to receive(:file?).with(path).and_return(false) + allow(File).to receive(:realpath?).with(path).and_return(resource_path) + allow(File).to receive(:exists?).with(path).and_return(false) + allow(File).to receive(:exist?).with(path).and_return(false) + allow(File).to receive(:directory?).with(path).and_return(false) + allow(File).to receive(:writable?).with(path).and_return(false) + allow(file_symlink_class).to receive(:symlink?).with(path).and_return(false) end - File.stub(:directory?).with(enclosing_directory).and_return(true) + allow(File).to receive(:directory?).with(enclosing_directory).and_return(true) end def setup_symlink [ resource_path, normalized_path, windows_path].each do |path| - File.stub(:file?).with(path).and_return(true) - File.stub(:realpath?).with(path).and_return(normalized_path) - File.stub(:exists?).with(path).and_return(true) - File.stub(:exist?).with(path).and_return(true) - File.stub(:directory?).with(path).and_return(false) - File.stub(:writable?).with(path).and_return(true) - file_symlink_class.stub(:symlink?).with(path).and_return(true) + allow(File).to receive(:file?).with(path).and_return(true) + allow(File).to receive(:realpath?).with(path).and_return(normalized_path) + allow(File).to receive(:exists?).with(path).and_return(true) + allow(File).to receive(:exist?).with(path).and_return(true) + allow(File).to receive(:directory?).with(path).and_return(false) + allow(File).to receive(:writable?).with(path).and_return(true) + allow(file_symlink_class).to receive(:symlink?).with(path).and_return(true) end - File.stub(:directory?).with(enclosing_directory).and_return(true) + allow(File).to receive(:directory?).with(enclosing_directory).and_return(true) end def setup_unwritable_file [ resource_path, normalized_path, windows_path].each do |path| - File.stub(:file?).with(path).and_return(false) - File.stub(:realpath?).with(path).and_raise(Errno::ENOENT) - File.stub(:exists?).with(path).and_return(true) - File.stub(:exist?).with(path).and_return(true) - File.stub(:directory?).with(path).and_return(false) - File.stub(:writable?).with(path).and_return(false) - file_symlink_class.stub(:symlink?).with(path).and_return(false) + allow(File).to receive(:file?).with(path).and_return(false) + allow(File).to receive(:realpath?).with(path).and_raise(Errno::ENOENT) + allow(File).to receive(:exists?).with(path).and_return(true) + allow(File).to receive(:exist?).with(path).and_return(true) + allow(File).to receive(:directory?).with(path).and_return(false) + allow(File).to receive(:writable?).with(path).and_return(false) + allow(file_symlink_class).to receive(:symlink?).with(path).and_return(false) end - File.stub(:directory?).with(enclosing_directory).and_return(true) + allow(File).to receive(:directory?).with(enclosing_directory).and_return(true) end def setup_missing_enclosing_directory [ resource_path, normalized_path, windows_path].each do |path| - File.stub(:file?).with(path).and_return(false) - File.stub(:realpath?).with(path).and_raise(Errno::ENOENT) - File.stub(:exists?).with(path).and_return(false) - File.stub(:exist?).with(path).and_return(false) - File.stub(:directory?).with(path).and_return(false) - File.stub(:writable?).with(path).and_return(false) - file_symlink_class.stub(:symlink?).with(path).and_return(false) + allow(File).to receive(:file?).with(path).and_return(false) + allow(File).to receive(:realpath?).with(path).and_raise(Errno::ENOENT) + allow(File).to receive(:exists?).with(path).and_return(false) + allow(File).to receive(:exist?).with(path).and_return(false) + allow(File).to receive(:directory?).with(path).and_return(false) + allow(File).to receive(:writable?).with(path).and_return(false) + allow(file_symlink_class).to receive(:symlink?).with(path).and_return(false) end - File.stub(:directory?).with(enclosing_directory).and_return(false) + allow(File).to receive(:directory?).with(enclosing_directory).and_return(false) end # A File subclass that we use as a replacement for Tempfile. Some versions of @@ -136,9 +136,9 @@ shared_examples_for Chef::Provider::File do end before(:each) do - content.stub(:tempfile).and_return(tempfile) - File.stub(:exist?).with(tempfile.path).and_call_original - File.stub(:exists?).with(tempfile.path).and_call_original + allow(content).to receive(:tempfile).and_return(tempfile) + allow(File).to receive(:exist?).with(tempfile.path).and_call_original + allow(File).to receive(:exists?).with(tempfile.path).and_call_original end after do @@ -147,15 +147,15 @@ shared_examples_for Chef::Provider::File do end it "should return a #{described_class}" do - provider.should be_a_kind_of(described_class) + expect(provider).to be_a_kind_of(described_class) end it "should store the resource passed to new as new_resource" do - provider.new_resource.should eql(resource) + expect(provider.new_resource).to eql(resource) end it "should store the node passed to new as node" do - provider.node.should eql(node) + expect(provider.node).to eql(node) end context "when loading the current resource" do @@ -167,15 +167,15 @@ shared_examples_for Chef::Provider::File do # it "should not try to load the content when the file is present" do setup_normal_file - provider.should_not_receive(:tempfile) - provider.should_not_receive(:content) + expect(provider).not_to receive(:tempfile) + expect(provider).not_to receive(:content) provider.load_current_resource end it "should not try to load the content when the file is missing" do setup_missing_file - provider.should_not_receive(:tempfile) - provider.should_not_receive(:content) + expect(provider).not_to receive(:tempfile) + expect(provider).not_to receive(:content) provider.load_current_resource end end @@ -189,33 +189,33 @@ shared_examples_for Chef::Provider::File do it "should load a current resource based on the one specified at construction" do provider.load_current_resource - provider.current_resource.should be_a_kind_of(Chef::Resource::File) + expect(provider.current_resource).to be_a_kind_of(Chef::Resource::File) end it "the loaded current_resource name should be the same as the resource name" do provider.load_current_resource - provider.current_resource.name.should eql(resource.name) + expect(provider.current_resource.name).to eql(resource.name) end it "the loaded current_resource path should be the same as the resoure path" do provider.load_current_resource - provider.current_resource.path.should eql(resource.path) + expect(provider.current_resource.path).to eql(resource.path) end it "the loaded current_resource content should be nil" do provider.load_current_resource - provider.current_resource.content.should eql(nil) + expect(provider.current_resource.content).to eql(nil) end it "it should call checksum if we are managing content" do - provider.should_receive(:managing_content?).at_least(:once).and_return(true) - provider.should_receive(:checksum).with(resource.path).and_return(tempfile_sha256) + expect(provider).to receive(:managing_content?).at_least(:once).and_return(true) + expect(provider).to receive(:checksum).with(resource.path).and_return(tempfile_sha256) provider.load_current_resource end it "it should not call checksum if we are not managing content" do - provider.should_receive(:managing_content?).at_least(:once).and_return(false) - provider.should_not_receive(:checksum) + expect(provider).to receive(:managing_content?).at_least(:once).and_return(false) + expect(provider).not_to receive(:checksum) provider.load_current_resource end end @@ -227,27 +227,27 @@ shared_examples_for Chef::Provider::File do it "the current_resource should be a Chef::Resource::File" do provider.load_current_resource - provider.current_resource.should be_a_kind_of(Chef::Resource::File) + expect(provider.current_resource).to be_a_kind_of(Chef::Resource::File) end it "the current_resource name should be the same as the resource name" do provider.load_current_resource - provider.current_resource.name.should eql(resource.name) + expect(provider.current_resource.name).to eql(resource.name) end it "the current_resource path should be the same as the resource path" do provider.load_current_resource - provider.current_resource.path.should eql(resource.path) + expect(provider.current_resource.path).to eql(resource.path) end it "the loaded current_resource content should be nil" do provider.load_current_resource - provider.current_resource.content.should eql(nil) + expect(provider.current_resource.content).to eql(nil) end it "it should not call checksum if we are not managing content" do - provider.should_not_receive(:managing_content?) - provider.should_not_receive(:checksum) + expect(provider).not_to receive(:managing_content?) + expect(provider).not_to receive(:checksum) provider.load_current_resource end end @@ -255,14 +255,14 @@ shared_examples_for Chef::Provider::File do context "examining file security metadata on Unix with a file that exists" do before do # fake that we're on unix even if we're on windows - Chef::Platform.stub(:windows?).and_return(false) + allow(Chef::Platform).to receive(:windows?).and_return(false) # mock up the filesystem to behave like unix setup_normal_file stat_struct = double("::File.stat", :mode => 0600, :uid => 0, :gid => 0, :mtime => 10000) resource_real_path = File.realpath(resource.path) - File.should_receive(:stat).with(resource_real_path).at_least(:once).and_return(stat_struct) - Etc.stub(:getgrgid).with(0).and_return(double("Group Ent", :name => "wheel")) - Etc.stub(:getpwuid).with(0).and_return(double("User Ent", :name => "root")) + expect(File).to receive(:stat).with(resource_real_path).at_least(:once).and_return(stat_struct) + allow(Etc).to receive(:getgrgid).with(0).and_return(double("Group Ent", :name => "wheel")) + allow(Etc).to receive(:getpwuid).with(0).and_return(double("User Ent", :name => "root")) end context "when the new_resource does not specify any state" do @@ -271,15 +271,15 @@ shared_examples_for Chef::Provider::File do end it "should load the permissions into the current_resource" do - provider.current_resource.mode.should == "0600" - provider.current_resource.owner.should == "root" - provider.current_resource.group.should == "wheel" + expect(provider.current_resource.mode).to eq("0600") + expect(provider.current_resource.owner).to eq("root") + expect(provider.current_resource.group).to eq("wheel") end it "should not set the new_resource permissions" do - provider.new_resource.group.should be_nil - provider.new_resource.owner.should be_nil - provider.new_resource.mode.should be_nil + expect(provider.new_resource.group).to be_nil + expect(provider.new_resource.owner).to be_nil + expect(provider.new_resource.mode).to be_nil end end @@ -293,15 +293,15 @@ shared_examples_for Chef::Provider::File do it "should load the permissions into the current_resource as numbers" do # Mode is always loaded as string for reporting purposes. - provider.current_resource.mode.should == "0600" - provider.current_resource.owner.should == 0 - provider.current_resource.group.should == 0 + expect(provider.current_resource.mode).to eq("0600") + expect(provider.current_resource.owner).to eq(0) + expect(provider.current_resource.group).to eq(0) end it "should not set the new_resource permissions" do - provider.new_resource.group.should == 1 - provider.new_resource.owner.should == 1 - provider.new_resource.mode.should == 0644 + expect(provider.new_resource.group).to eq(1) + expect(provider.new_resource.owner).to eq(1) + expect(provider.new_resource.mode).to eq(0644) end end @@ -314,15 +314,15 @@ shared_examples_for Chef::Provider::File do end it "should load the permissions into the current_resource as symbols" do - provider.current_resource.mode.should == "0600" - provider.current_resource.owner.should == "root" - provider.current_resource.group.should == "wheel" + expect(provider.current_resource.mode).to eq("0600") + expect(provider.current_resource.owner).to eq("root") + expect(provider.current_resource.group).to eq("wheel") end it "should not set the new_resource permissions" do - provider.new_resource.group.should == "seattlehiphop" - provider.new_resource.owner.should == "macklemore" - provider.new_resource.mode.should == "0321" + expect(provider.new_resource.group).to eq("seattlehiphop") + expect(provider.new_resource.owner).to eq("macklemore") + expect(provider.new_resource.mode).to eq("0321") end end @@ -331,7 +331,7 @@ shared_examples_for Chef::Provider::File do context "examining file security metadata on Unix with a file that does not exist" do before do # fake that we're on unix even if we're on windows - Chef::Platform.stub(:windows?).and_return(false) + allow(Chef::Platform).to receive(:windows?).and_return(false) setup_missing_file end @@ -341,15 +341,15 @@ shared_examples_for Chef::Provider::File do end it "the current_resource permissions should be nil" do - provider.current_resource.mode.should be_nil - provider.current_resource.owner.should be_nil - provider.current_resource.group.should be_nil + expect(provider.current_resource.mode).to be_nil + expect(provider.current_resource.owner).to be_nil + expect(provider.current_resource.group).to be_nil end it "should not set the new_resource permissions" do - provider.new_resource.group.should be_nil - provider.new_resource.owner.should be_nil - provider.new_resource.mode.should be_nil + expect(provider.new_resource.group).to be_nil + expect(provider.new_resource.owner).to be_nil + expect(provider.new_resource.mode).to be_nil end end @@ -362,15 +362,15 @@ shared_examples_for Chef::Provider::File do end it "the current_resource permissions should be nil" do - provider.current_resource.mode.should be_nil - provider.current_resource.owner.should be_nil - provider.current_resource.group.should be_nil + expect(provider.current_resource.mode).to be_nil + expect(provider.current_resource.owner).to be_nil + expect(provider.current_resource.group).to be_nil end it "should not set the new_resource permissions" do - provider.new_resource.group.should == 51948 - provider.new_resource.owner.should == 63945 - provider.new_resource.mode.should == 0123 + expect(provider.new_resource.group).to eq(51948) + expect(provider.new_resource.owner).to eq(63945) + expect(provider.new_resource.mode).to eq(0123) end end end @@ -380,35 +380,35 @@ shared_examples_for Chef::Provider::File do before do # fake that we're on unix even if we're on windows - Chef::Platform.stub(:windows?).and_return(false) + allow(Chef::Platform).to receive(:windows?).and_return(false) # mock up the filesystem to behave like unix setup_normal_file stat_struct = double("::File.stat", :mode => 0600, :uid => 0, :gid => 0, :mtime => 10000) resource_real_path = File.realpath(resource.path) - File.stub(:stat).with(resource_real_path).and_return(stat_struct) - Etc.stub(:getgrgid).with(0).and_return(double("Group Ent", :name => "wheel")) - Etc.stub(:getpwuid).with(0).and_return(double("User Ent", :name => "root")) + allow(File).to receive(:stat).with(resource_real_path).and_return(stat_struct) + allow(Etc).to receive(:getgrgid).with(0).and_return(double("Group Ent", :name => "wheel")) + allow(Etc).to receive(:getpwuid).with(0).and_return(double("User Ent", :name => "root")) provider.send(:load_resource_attributes_from_file, resource) end it "new_resource should record the new permission information" do - provider.new_resource.group.should == "wheel" - provider.new_resource.owner.should == "root" - provider.new_resource.mode.should == "0600" + expect(provider.new_resource.group).to eq("wheel") + expect(provider.new_resource.owner).to eq("root") + expect(provider.new_resource.mode).to eq("0600") end end context "when reporting security metadata on windows" do it "records the file owner" do - pending + skip end it "records rights for each user in the ACL" do - pending + skip end it "records deny_rights for each user in the ACL" do - pending + skip end end @@ -419,12 +419,12 @@ shared_examples_for Chef::Provider::File do [:create, :create_if_missing, :touch].each do |action| context "action #{action}" do it "raises EnclosingDirectoryDoesNotExist" do - lambda {provider.run_action(action)}.should raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist) + expect {provider.run_action(action)}.to raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist) end it "does not raise an exception in why-run mode" do Chef::Config[:why_run] = true - lambda {provider.run_action(action)}.should_not raise_error + expect {provider.run_action(action)}.not_to raise_error Chef::Config[:why_run] = false end end @@ -435,12 +435,12 @@ shared_examples_for Chef::Provider::File do before { setup_unwritable_file } it "action delete raises InsufficientPermissions" do - lambda {provider.run_action(:delete)}.should raise_error(Chef::Exceptions::InsufficientPermissions) + expect {provider.run_action(:delete)}.to raise_error(Chef::Exceptions::InsufficientPermissions) end it "action delete also raises InsufficientPermissions in why-run mode" do Chef::Config[:why_run] = true - lambda {provider.run_action(:delete)}.should raise_error(Chef::Exceptions::InsufficientPermissions) + expect {provider.run_action(:delete)}.to raise_error(Chef::Exceptions::InsufficientPermissions) Chef::Config[:why_run] = false end end @@ -449,10 +449,10 @@ shared_examples_for Chef::Provider::File do context "action create" do it "should create the file, update its contents and then set the acls on the file" do setup_missing_file - provider.should_receive(:do_create_file) - provider.should_receive(:do_contents_changes) - provider.should_receive(:do_acl_changes) - provider.should_receive(:load_resource_attributes_from_file) + expect(provider).to receive(:do_create_file) + expect(provider).to receive(:do_contents_changes) + expect(provider).to receive(:do_acl_changes) + expect(provider).to receive(:load_resource_attributes_from_file) provider.run_action(:create) end @@ -461,18 +461,18 @@ shared_examples_for Chef::Provider::File do before { setup_normal_file } it "should not create the file" do provider.load_current_resource - provider.deployment_strategy.should_not_receive(:create).with(resource_path) + expect(provider.deployment_strategy).not_to receive(:create).with(resource_path) provider.send(:do_create_file) - provider.send(:needs_creating?).should == false + expect(provider.send(:needs_creating?)).to eq(false) end end context "when the file does not exist" do before { setup_missing_file } it "should create the file" do provider.load_current_resource - provider.deployment_strategy.should_receive(:create).with(resource_path) + expect(provider.deployment_strategy).to receive(:create).with(resource_path) provider.send(:do_create_file) - provider.send(:needs_creating?).should == true + expect(provider.send(:needs_creating?)).to eq(true) end end end @@ -483,10 +483,10 @@ shared_examples_for Chef::Provider::File do setup_normal_file provider.load_current_resource tempfile = double('Tempfile', :path => "/tmp/foo-bar-baz") - content.stub(:tempfile).and_return(tempfile) - File.should_receive(:exists?).with("/tmp/foo-bar-baz").and_return(true) - tempfile.should_receive(:close).once - tempfile.should_receive(:unlink).once + allow(content).to receive(:tempfile).and_return(tempfile) + expect(File).to receive(:exists?).with("/tmp/foo-bar-baz").and_return(true) + expect(tempfile).to receive(:close).once + expect(tempfile).to receive(:unlink).once end context "when the contents have changed" do @@ -494,64 +494,64 @@ shared_examples_for Chef::Provider::File do let(:tempfile_sha256) { "42971f0ddce0cb20cf7660a123ffa1a1543beb2f1e7cd9d65858764a27f3201d" } let(:diff_for_reporting) { "+++\n---\n+foo\n-bar\n" } before do - provider.stub(:contents_changed?).and_return(true) + allow(provider).to receive(:contents_changed?).and_return(true) diff = double('Diff', :for_output => ['+++','---','+foo','-bar'], :for_reporting => diff_for_reporting ) - diff.stub(:diff).with(resource_path, tempfile_path).and_return(true) - provider.should_receive(:diff).at_least(:once).and_return(diff) - provider.should_receive(:managing_content?).at_least(:once).and_return(true) - provider.should_receive(:checksum).with(tempfile_path).and_return(tempfile_sha256) - provider.should_receive(:checksum).with(resource_path).and_return(tempfile_sha256) - provider.deployment_strategy.should_receive(:deploy).with(tempfile_path, normalized_path) + allow(diff).to receive(:diff).with(resource_path, tempfile_path).and_return(true) + expect(provider).to receive(:diff).at_least(:once).and_return(diff) + expect(provider).to receive(:managing_content?).at_least(:once).and_return(true) + expect(provider).to receive(:checksum).with(tempfile_path).and_return(tempfile_sha256) + expect(provider).to receive(:checksum).with(resource_path).and_return(tempfile_sha256) + expect(provider.deployment_strategy).to receive(:deploy).with(tempfile_path, normalized_path) end context "when the file was created" do - before { provider.should_receive(:needs_creating?).at_least(:once).and_return(true) } + before { expect(provider).to receive(:needs_creating?).at_least(:once).and_return(true) } it "does not backup the file and does not produce a diff for reporting" do - provider.should_not_receive(:do_backup) + expect(provider).not_to receive(:do_backup) provider.send(:do_contents_changes) - resource.diff.should be_nil + expect(resource.diff).to be_nil end end context "when the file was not created" do - before { provider.should_receive(:needs_creating?).at_least(:once).and_return(false) } + before { expect(provider).to receive(:needs_creating?).at_least(:once).and_return(false) } it "backs up the file and produces a diff for reporting" do - provider.should_receive(:do_backup) + expect(provider).to receive(:do_backup) provider.send(:do_contents_changes) - resource.diff.should == diff_for_reporting + expect(resource.diff).to eq(diff_for_reporting) end end end it "does nothing when the contents have not changed" do - provider.stub(:contents_changed?).and_return(false) - provider.should_not_receive(:diff) + allow(provider).to receive(:contents_changed?).and_return(false) + expect(provider).not_to receive(:diff) provider.send(:do_contents_changes) end end it "does nothing when there is no content to deploy (tempfile returned from contents is nil)" do - provider.send(:content).should_receive(:tempfile).at_least(:once).and_return(nil) - provider.should_not_receive(:diff) - lambda{ provider.send(:do_contents_changes) }.should_not raise_error + expect(provider.send(:content)).to receive(:tempfile).at_least(:once).and_return(nil) + expect(provider).not_to receive(:diff) + expect{ provider.send(:do_contents_changes) }.not_to raise_error end it "raises an exception when the content object returns a tempfile with a nil path" do tempfile = double('Tempfile', :path => nil) - provider.send(:content).should_receive(:tempfile).at_least(:once).and_return(tempfile) - lambda{ provider.send(:do_contents_changes) }.should raise_error + expect(provider.send(:content)).to receive(:tempfile).at_least(:once).and_return(tempfile) + expect{ provider.send(:do_contents_changes) }.to raise_error end it "raises an exception when the content object returns a tempfile that does not exist" do tempfile = double('Tempfile', :path => "/tmp/foo-bar-baz") - provider.send(:content).should_receive(:tempfile).at_least(:once).and_return(tempfile) - File.should_receive(:exists?).with("/tmp/foo-bar-baz").and_return(false) - lambda{ provider.send(:do_contents_changes) }.should raise_error + expect(provider.send(:content)).to receive(:tempfile).at_least(:once).and_return(tempfile) + expect(File).to receive(:exists?).with("/tmp/foo-bar-baz").and_return(false) + expect{ provider.send(:do_contents_changes) }.to raise_error end end context "do_acl_changes" do it "needs tests" do - pending + skip end end @@ -560,11 +560,11 @@ shared_examples_for Chef::Provider::File do before do setup_normal_file provider.load_current_resource - provider.stub(:resource_updated?).and_return(true) + allow(provider).to receive(:resource_updated?).and_return(true) end it "should check for selinux_enabled? by default" do - provider.should_receive(:selinux_enabled?) + expect(provider).to receive(:selinux_enabled?) provider.send(:do_selinux) end @@ -580,27 +580,27 @@ shared_examples_for Chef::Provider::File do context "when selinux is enabled on the system" do before do - provider.should_receive(:selinux_enabled?).and_return(true) + expect(provider).to receive(:selinux_enabled?).and_return(true) end it "restores security context on the file" do - provider.should_receive(:restore_security_context).with(normalized_path, false) + expect(provider).to receive(:restore_security_context).with(normalized_path, false) provider.send(:do_selinux) end it "restores security context recursively when told so" do - provider.should_receive(:restore_security_context).with(normalized_path, true) + expect(provider).to receive(:restore_security_context).with(normalized_path, true) provider.send(:do_selinux, true) end end context "when selinux is disabled on the system" do before do - provider.should_receive(:selinux_enabled?).and_return(false) + expect(provider).to receive(:selinux_enabled?).and_return(false) end it "should not restore security context" do - provider.should_not_receive(:restore_security_context) + expect(provider).not_to receive(:restore_security_context) provider.send(:do_selinux) end end @@ -617,7 +617,7 @@ shared_examples_for Chef::Provider::File do end it "should not check for selinux_enabled?" do - provider.should_not_receive(:selinux_enabled?) + expect(provider).not_to receive(:selinux_enabled?) provider.send(:do_selinux) end end @@ -625,11 +625,11 @@ shared_examples_for Chef::Provider::File do context "when resource is not updated" do before do - provider.stub(:resource_updated?).and_return(false) + allow(provider).to receive(:resource_updated?).and_return(false) end it "should not check for selinux_enabled?" do - provider.should_not_receive(:selinux_enabled?) + expect(provider).not_to receive(:selinux_enabled?) provider.send(:do_selinux) end end @@ -643,29 +643,29 @@ shared_examples_for Chef::Provider::File do context "when the file is not a symlink" do before { setup_normal_file } it "should backup and delete the file and be updated by the last action" do - provider.should_receive(:do_backup).at_least(:once).and_return(true) - File.should_receive(:delete).with(resource_path).and_return(true) + expect(provider).to receive(:do_backup).at_least(:once).and_return(true) + expect(File).to receive(:delete).with(resource_path).and_return(true) provider.run_action(:delete) - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end context "when the file is a symlink" do before { setup_symlink } it "should not backup the symlink" do - provider.should_not_receive(:do_backup) - File.should_receive(:delete).with(resource_path).and_return(true) + expect(provider).not_to receive(:do_backup) + expect(File).to receive(:delete).with(resource_path).and_return(true) provider.run_action(:delete) - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end end context "when the file is not writable" do before { setup_unwritable_file } it "should not try to backup or delete the file, and should not be updated by last action" do - provider.should_not_receive(:do_backup) - File.should_not_receive(:delete) - lambda { provider.run_action(:delete) }.should raise_error() - resource.should_not be_updated_by_last_action + expect(provider).not_to receive(:do_backup) + expect(File).not_to receive(:delete) + expect { provider.run_action(:delete) }.to raise_error() + expect(resource).not_to be_updated_by_last_action end end end @@ -674,10 +674,10 @@ shared_examples_for Chef::Provider::File do before { setup_missing_file } it "should not try to backup or delete the file, and should not be updated by last action" do - provider.should_not_receive(:do_backup) - File.should_not_receive(:delete) - lambda { provider.run_action(:delete) }.should_not raise_error - resource.should_not be_updated_by_last_action + expect(provider).not_to receive(:do_backup) + expect(File).not_to receive(:delete) + expect { provider.run_action(:delete) }.not_to raise_error + expect(resource).not_to be_updated_by_last_action end end end @@ -686,19 +686,19 @@ shared_examples_for Chef::Provider::File do context "when the file does not exist" do before { setup_missing_file } it "should update the atime/mtime on action_touch" do - File.should_receive(:utime).once - provider.should_receive(:action_create) + expect(File).to receive(:utime).once + expect(provider).to receive(:action_create) provider.run_action(:touch) - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end context "when the file exists" do before { setup_normal_file } it "should update the atime/mtime on action_touch" do - File.should_receive(:utime).once - provider.should_receive(:action_create) + expect(File).to receive(:utime).once + expect(provider).to receive(:action_create) provider.run_action(:touch) - resource.should be_updated_by_last_action + expect(resource).to be_updated_by_last_action end end end @@ -707,7 +707,7 @@ shared_examples_for Chef::Provider::File do context "when the file does not exist" do before { setup_missing_file } it "should call action_create" do - provider.should_receive(:action_create) + expect(provider).to receive(:action_create) provider.run_action(:create_if_missing) end end @@ -715,7 +715,7 @@ shared_examples_for Chef::Provider::File do context "when the file exists" do before { setup_normal_file } it "should not call action_create" do - provider.should_not_receive(:action_create) + expect(provider).not_to receive(:action_create) provider.run_action(:create_if_missing) end end @@ -728,27 +728,27 @@ shared_examples_for "a file provider with content field" do context "when testing managing_content?" do it "should be false when creating a file without content" do provider.action = :create - resource.stub(:content).and_return(nil) - resource.stub(:checksum).and_return(nil) - expect(provider.send(:managing_content?)).to be_false + allow(resource).to receive(:content).and_return(nil) + allow(resource).to receive(:checksum).and_return(nil) + expect(provider.send(:managing_content?)).to be_falsey end it "should be true when creating a file with content" do provider.action = :create - resource.stub(:content).and_return("flurbleblobbleblooble") - resource.stub(:checksum).and_return(nil) - expect(provider.send(:managing_content?)).to be_true + allow(resource).to receive(:content).and_return("flurbleblobbleblooble") + allow(resource).to receive(:checksum).and_return(nil) + expect(provider.send(:managing_content?)).to be_truthy end it "should be true when checksum is set on the content (no matter how crazy)" do provider.action = :create_if_missing - resource.stub(:checksum).and_return("1234123234234234") - resource.stub(:content).and_return(nil) - expect(provider.send(:managing_content?)).to be_true + allow(resource).to receive(:checksum).and_return("1234123234234234") + allow(resource).to receive(:content).and_return(nil) + expect(provider.send(:managing_content?)).to be_truthy end it "should be false when action is create_if_missing" do provider.action = :create_if_missing - resource.stub(:content).and_return("flurbleblobbleblooble") - resource.stub(:checksum).and_return(nil) - expect(provider.send(:managing_content?)).to be_false + allow(resource).to receive(:content).and_return("flurbleblobbleblooble") + allow(resource).to receive(:checksum).and_return(nil) + expect(provider.send(:managing_content?)).to be_falsey end end end @@ -757,32 +757,31 @@ shared_examples_for "a file provider with source field" do context "when testing managing_content?" do it "should be false when creating a file without content" do provider.action = :create - resource.stub(:content).and_return(nil) - resource.stub(:source).and_return(nil) - resource.stub(:checksum).and_return(nil) - expect(provider.send(:managing_content?)).to be_false + allow(resource).to receive(:content).and_return(nil) + allow(resource).to receive(:source).and_return(nil) + allow(resource).to receive(:checksum).and_return(nil) + expect(provider.send(:managing_content?)).to be_falsey end it "should be true when creating a file with content" do provider.action = :create - resource.stub(:content).and_return(nil) - resource.stub(:source).and_return("http://somewhere.com/something.php") - resource.stub(:checksum).and_return(nil) - expect(provider.send(:managing_content?)).to be_true + allow(resource).to receive(:content).and_return(nil) + allow(resource).to receive(:source).and_return("http://somewhere.com/something.php") + allow(resource).to receive(:checksum).and_return(nil) + expect(provider.send(:managing_content?)).to be_truthy end it "should be true when checksum is set on the content (no matter how crazy)" do provider.action = :create_if_missing - resource.stub(:content).and_return(nil) - resource.stub(:source).and_return(nil) - resource.stub(:checksum).and_return("1234123234234234") - expect(provider.send(:managing_content?)).to be_true + allow(resource).to receive(:content).and_return(nil) + allow(resource).to receive(:source).and_return(nil) + allow(resource).to receive(:checksum).and_return("1234123234234234") + expect(provider.send(:managing_content?)).to be_truthy end it "should be false when action is create_if_missing" do provider.action = :create_if_missing - resource.stub(:content).and_return(nil) - resource.stub(:source).and_return("http://somewhere.com/something.php") - resource.stub(:checksum).and_return(nil) - expect(provider.send(:managing_content?)).to be_false + allow(resource).to receive(:content).and_return(nil) + allow(resource).to receive(:source).and_return("http://somewhere.com/something.php") + allow(resource).to receive(:checksum).and_return(nil) + expect(provider.send(:managing_content?)).to be_falsey end end end - diff --git a/spec/support/shared/unit/provider/useradd_based_user_provider.rb b/spec/support/shared/unit/provider/useradd_based_user_provider.rb index 42f948d494..fc7c79ef7d 100644 --- a/spec/support/shared/unit/provider/useradd_based_user_provider.rb +++ b/spec/support/shared/unit/provider/useradd_based_user_provider.rb @@ -53,39 +53,39 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option supported_useradd_options.each do |attribute, option| it "should check for differences in #{attribute} between the new and current resources" do - @current_resource.should_receive(attribute) - @new_resource.should_receive(attribute) + expect(@current_resource).to receive(attribute) + expect(@new_resource).to receive(attribute) provider.universal_options end it "should set the option for #{attribute} if the new resources #{attribute} is not nil" do - @new_resource.stub(attribute).and_return("hola") - provider.universal_options.should eql([option, 'hola']) + allow(@new_resource).to receive(attribute).and_return("hola") + expect(provider.universal_options).to eql([option, 'hola']) end it "should set the option for #{attribute} if the new resources #{attribute} is not nil, without homedir management" do - @new_resource.stub(:supports).and_return({:manage_home => false, + allow(@new_resource).to receive(:supports).and_return({:manage_home => false, :non_unique => false}) - @new_resource.stub(attribute).and_return("hola") - provider.universal_options.should eql([option, 'hola']) + allow(@new_resource).to receive(attribute).and_return("hola") + expect(provider.universal_options).to eql([option, 'hola']) end it "should set the option for #{attribute} if the new resources #{attribute} is not nil, without homedir management (using real attributes)" do - @new_resource.stub(:manage_home).and_return(false) - @new_resource.stub(:non_unique).and_return(false) - @new_resource.stub(:non_unique).and_return(false) - @new_resource.stub(attribute).and_return("hola") - provider.universal_options.should eql([option, 'hola']) + allow(@new_resource).to receive(:manage_home).and_return(false) + allow(@new_resource).to receive(:non_unique).and_return(false) + allow(@new_resource).to receive(:non_unique).and_return(false) + allow(@new_resource).to receive(attribute).and_return("hola") + expect(provider.universal_options).to eql([option, 'hola']) end end it "should combine all the possible options" do combined_opts = [] supported_useradd_options.sort{ |a,b| a[0] <=> b[0] }.each do |attribute, option| - @new_resource.stub(attribute).and_return("hola") + allow(@new_resource).to receive(attribute).and_return("hola") combined_opts << option << 'hola' end - provider.universal_options.should eql(combined_opts) + expect(provider.universal_options).to eql(combined_opts) end describe "when we want to create a system user" do @@ -96,55 +96,55 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option it "should set useradd -r" do @new_resource.system(true) - provider.useradd_options.should == [ "-r" ] + expect(provider.useradd_options).to eq([ "-r" ]) end end describe "when the resource has a different home directory and supports home directory management" do before do - @new_resource.stub(:home).and_return("/wowaweea") - @new_resource.stub(:supports).and_return({:manage_home => true, + allow(@new_resource).to receive(:home).and_return("/wowaweea") + allow(@new_resource).to receive(:supports).and_return({:manage_home => true, :non_unique => false}) end it "should set -m -d /homedir" do - provider.universal_options.should == %w[-d /wowaweea -m] - provider.useradd_options.should == [] + expect(provider.universal_options).to eq(%w[-d /wowaweea -m]) + expect(provider.useradd_options).to eq([]) end end describe "when the resource has a different home directory and supports home directory management (using real attributes)" do before do - @new_resource.stub(:home).and_return("/wowaweea") - @new_resource.stub(:manage_home).and_return(true) - @new_resource.stub(:non_unique).and_return(false) + allow(@new_resource).to receive(:home).and_return("/wowaweea") + allow(@new_resource).to receive(:manage_home).and_return(true) + allow(@new_resource).to receive(:non_unique).and_return(false) end it "should set -m -d /homedir" do - provider.universal_options.should eql(%w[-d /wowaweea -m]) - provider.useradd_options.should == [] + expect(provider.universal_options).to eql(%w[-d /wowaweea -m]) + expect(provider.useradd_options).to eq([]) end end describe "when the resource supports non_unique ids" do before do - @new_resource.stub(:supports).and_return({:manage_home => false, + allow(@new_resource).to receive(:supports).and_return({:manage_home => false, :non_unique => true}) end it "should set -m -o" do - provider.universal_options.should eql([ "-o" ]) + expect(provider.universal_options).to eql([ "-o" ]) end end describe "when the resource supports non_unique ids (using real attributes)" do before do - @new_resource.stub(:manage_home).and_return(false) - @new_resource.stub(:non_unique).and_return(true) + allow(@new_resource).to receive(:manage_home).and_return(false) + allow(@new_resource).to receive(:non_unique).and_return(true) end it "should set -m -o" do - provider.universal_options.should eql([ "-o" ]) + expect(provider.universal_options).to eql([ "-o" ]) end end end @@ -169,7 +169,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option "-d", '/Users/mud', "-m", "adam" ]) - provider.should_receive(:shell_out!).with(*command).and_return(true) + expect(provider).to receive(:shell_out!).with(*command).and_return(true) provider.create_user end @@ -190,7 +190,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option "-u", '1000', "-r", "adam" ]) - provider.should_receive(:shell_out!).with(*command).and_return(true) + expect(provider).to receive(:shell_out!).with(*command).and_return(true) provider.create_user end @@ -213,7 +213,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option "-d", '/Users/mud', "-m", "adam" ] - provider.should_receive(:shell_out!).with(*command).and_return(true) + expect(provider).to receive(:shell_out!).with(*command).and_return(true) provider.manage_user end @@ -224,16 +224,16 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option "-d", '/Users/mud', "-m", "adam" ] - provider.should_receive(:shell_out!).with(*command).and_return(true) + expect(provider).to receive(:shell_out!).with(*command).and_return(true) provider.manage_user end it "CHEF-3429: does not set -m if we aren't changing the home directory" do - provider.should_receive(:updating_home?).and_return(false) + expect(provider).to receive(:updating_home?).and_return(false) command = ["usermod", "-g", '23', "adam" ] - provider.should_receive(:shell_out!).with(*command).and_return(true) + expect(provider).to receive(:shell_out!).with(*command).and_return(true) provider.manage_user end end @@ -241,27 +241,27 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option describe "when removing a user" do it "should run userdel with the new resources user name" do - provider.should_receive(:shell_out!).with("userdel", @new_resource.username).and_return(true) + expect(provider).to receive(:shell_out!).with("userdel", @new_resource.username).and_return(true) provider.remove_user end it "should run userdel with the new resources user name and -r if manage_home is true" do @new_resource.supports({ :manage_home => true, :non_unique => false}) - provider.should_receive(:shell_out!).with("userdel", "-r", @new_resource.username).and_return(true) + expect(provider).to receive(:shell_out!).with("userdel", "-r", @new_resource.username).and_return(true) provider.remove_user end it "should run userdel with the new resources user name if non_unique is true" do @new_resource.supports({ :manage_home => false, :non_unique => true}) - provider.should_receive(:shell_out!).with("userdel", @new_resource.username).and_return(true) + expect(provider).to receive(:shell_out!).with("userdel", @new_resource.username).and_return(true) provider.remove_user end it "should run userdel with the new resources user name and -f if force is true" do @new_resource.force(true) - provider.should_receive(:shell_out!).with("userdel", "-f", @new_resource.username).and_return(true) + expect(provider).to receive(:shell_out!).with("userdel", "-f", @new_resource.username).and_return(true) provider.remove_user end end @@ -284,96 +284,96 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option end it "should return false if status begins with P" do - provider.should_receive(:shell_out!). + expect(provider).to receive(:shell_out!). with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). and_return(passwd_s_status) - provider.check_lock.should eql(false) + expect(provider.check_lock).to eql(false) end it "should return false if status begins with N" do @stdout = "root N" - provider.should_receive(:shell_out!). + expect(provider).to receive(:shell_out!). with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). and_return(passwd_s_status) - provider.check_lock.should eql(false) + expect(provider.check_lock).to eql(false) end it "should return true if status begins with L" do @stdout = "root L" - provider.should_receive(:shell_out!). + expect(provider).to receive(:shell_out!). with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). and_return(passwd_s_status) - provider.check_lock.should eql(true) + expect(provider.check_lock).to eql(true) end it "should raise a Chef::Exceptions::User if passwd -S fails on anything other than redhat/centos" do @node.automatic_attrs[:platform] = 'ubuntu' - provider.should_receive(:shell_out!). + expect(provider).to receive(:shell_out!). with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). and_return(passwd_s_status) - passwd_s_status.should_receive(:exitstatus).and_return(1) - lambda { provider.check_lock }.should raise_error(Chef::Exceptions::User) + expect(passwd_s_status).to receive(:exitstatus).and_return(1) + expect { provider.check_lock }.to raise_error(Chef::Exceptions::User) end ['redhat', 'centos'].each do |os| it "should not raise a Chef::Exceptions::User if passwd -S exits with 1 on #{os} and the passwd package is version 0.73-1" do @node.automatic_attrs[:platform] = os - passwd_s_status.should_receive(:exitstatus).and_return(1) - provider.should_receive(:shell_out!). + expect(passwd_s_status).to receive(:exitstatus).and_return(1) + expect(provider).to receive(:shell_out!). with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). and_return(passwd_s_status) rpm_status = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => "passwd-0.73-1\n", :stderr => "") - provider.should_receive(:shell_out!).with("rpm -q passwd").and_return(rpm_status) - lambda { provider.check_lock }.should_not raise_error + expect(provider).to receive(:shell_out!).with("rpm -q passwd").and_return(rpm_status) + expect { provider.check_lock }.not_to raise_error end it "should raise a Chef::Exceptions::User if passwd -S exits with 1 on #{os} and the passwd package is not version 0.73-1" do @node.automatic_attrs[:platform] = os - passwd_s_status.should_receive(:exitstatus).and_return(1) - provider.should_receive(:shell_out!). + expect(passwd_s_status).to receive(:exitstatus).and_return(1) + expect(provider).to receive(:shell_out!). with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). and_return(passwd_s_status) rpm_status = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => "passwd-0.73-2\n", :stderr => "") - provider.should_receive(:shell_out!).with("rpm -q passwd").and_return(rpm_status) - lambda { provider.check_lock }.should raise_error(Chef::Exceptions::User) + expect(provider).to receive(:shell_out!).with("rpm -q passwd").and_return(rpm_status) + expect { provider.check_lock }.to raise_error(Chef::Exceptions::User) end it "should raise a ShellCommandFailed exception if passwd -S exits with something other than 0 or 1 on #{os}" do @node.automatic_attrs[:platform] = os - provider.should_receive(:shell_out!).and_raise(Mixlib::ShellOut::ShellCommandFailed) - lambda { provider.check_lock }.should raise_error(Mixlib::ShellOut::ShellCommandFailed) + expect(provider).to receive(:shell_out!).and_raise(Mixlib::ShellOut::ShellCommandFailed) + expect { provider.check_lock }.to raise_error(Mixlib::ShellOut::ShellCommandFailed) end end context "when in why run mode" do before do passwd_status = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => "", :stderr => "passwd: user 'chef-test' does not exist\n") - provider.should_receive(:shell_out!). + expect(provider).to receive(:shell_out!). with("passwd", "-S", @new_resource.username, {:returns=>[0, 1]}). and_return(passwd_status) Chef::Config[:why_run] = true end it "should return false if the user does not exist" do - provider.check_lock.should eql(false) + expect(provider.check_lock).to eql(false) end it "should not raise an error if the user does not exist" do - lambda { provider.check_lock }.should_not raise_error + expect { provider.check_lock }.not_to raise_error end end end describe "when locking the user" do it "should run usermod -L with the new resources username" do - provider.should_receive(:shell_out!).with("usermod", "-L", @new_resource.username) + expect(provider).to receive(:shell_out!).with("usermod", "-L", @new_resource.username) provider.lock_user end end describe "when unlocking the user" do it "should run usermod -L with the new resources username" do - provider.should_receive(:shell_out!).with("usermod", "-U", @new_resource.username) + expect(provider).to receive(:shell_out!).with("usermod", "-U", @new_resource.username) provider.unlock_user end end @@ -411,12 +411,12 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option provider.new_resource.home home_check["new_resource_home"].first @new_home_mock = double("Pathname") - Pathname.should_receive(:new).with(@current_resource.home).and_return(@current_home_mock) - @current_home_mock.should_receive(:cleanpath).and_return(home_check["current_resource_home"].last) - Pathname.should_receive(:new).with(@new_resource.home).and_return(@new_home_mock) - @new_home_mock.should_receive(:cleanpath).and_return(home_check["new_resource_home"].last) + expect(Pathname).to receive(:new).with(@current_resource.home).and_return(@current_home_mock) + expect(@current_home_mock).to receive(:cleanpath).and_return(home_check["current_resource_home"].last) + expect(Pathname).to receive(:new).with(@new_resource.home).and_return(@new_home_mock) + expect(@new_home_mock).to receive(:cleanpath).and_return(home_check["new_resource_home"].last) - provider.updating_home?.should == home_check["expected_result"] + expect(provider.updating_home?).to eq(home_check["expected_result"]) end end it "should return true if the current home does not exist but a home is specified by the new resource" do @@ -427,7 +427,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option @current_resource.home nil @new_resource.home "/home/kitten" - provider.updating_home?.should == true + expect(provider.updating_home?).to eq(true) end end end diff --git a/spec/support/shared/unit/script_resource.rb b/spec/support/shared/unit/script_resource.rb index a34f930fc8..58f7f98f19 100644 --- a/spec/support/shared/unit/script_resource.rb +++ b/spec/support/shared/unit/script_resource.rb @@ -26,26 +26,26 @@ shared_examples_for "a script resource" do end it "should create a new Chef::Resource::Script" do - @resource.should be_a_kind_of(Chef::Resource) - @resource.should be_a_kind_of(Chef::Resource::Script) + expect(@resource).to be_a_kind_of(Chef::Resource) + expect(@resource).to be_a_kind_of(Chef::Resource::Script) end it "should have a resource name of :script" do - @resource.resource_name.should eql(resource_name) + expect(@resource.resource_name).to eql(resource_name) end it "should set command to the argument provided to new" do - @resource.command.should eql(resource_instance_name) + expect(@resource.command).to eql(resource_instance_name) end it "should accept a string for the code" do @resource.code "hey jude" - @resource.code.should eql("hey jude") + expect(@resource.code).to eql("hey jude") end it "should accept a string for the flags" do @resource.flags "-f" - @resource.flags.should eql("-f") + expect(@resource.flags).to eql("-f") end describe "when executing guards" do @@ -67,23 +67,23 @@ shared_examples_for "a script resource" do inherited_difference = Chef::Resource::Script.guard_inherited_attributes - [:cwd, :environment, :group, :path, :user, :umask ] - inherited_difference.should == [] + expect(inherited_difference).to eq([]) end it "when guard_interpreter is set to the default value, the guard command string should be evaluated by command execution and not through a resource" do - Chef::Resource::Conditional.any_instance.should_not_receive(:evaluate_block) - Chef::GuardInterpreter::ResourceGuardInterpreter.any_instance.should_not_receive(:evaluate_action) - Chef::GuardInterpreter::DefaultGuardInterpreter.any_instance.should_receive(:evaluate).and_return(true) + expect_any_instance_of(Chef::Resource::Conditional).not_to receive(:evaluate_block) + expect_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).not_to receive(:evaluate_action) + expect_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).to receive(:evaluate).and_return(true) resource.only_if 'echo hi' - resource.should_skip?(:run).should == nil + expect(resource.should_skip?(:run)).to eq(nil) end it "when a valid guard_interpreter resource is specified, a block should be used to evaluate the guard" do - Chef::GuardInterpreter::DefaultGuardInterpreter.any_instance.should_not_receive(:evaluate) - Chef::GuardInterpreter::ResourceGuardInterpreter.any_instance.should_receive(:evaluate_action).and_return(true) + expect_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).not_to receive(:evaluate) + expect_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:evaluate_action).and_return(true) resource.guard_interpreter :script resource.only_if 'echo hi' - resource.should_skip?(:run).should == nil + expect(resource.should_skip?(:run)).to eq(nil) end end end diff --git a/spec/support/shared/unit/windows_script_resource.rb b/spec/support/shared/unit/windows_script_resource.rb index 888ad600c5..a2fc884ff2 100644 --- a/spec/support/shared/unit/windows_script_resource.rb +++ b/spec/support/shared/unit/windows_script_resource.rb @@ -35,30 +35,30 @@ shared_examples_for "a Windows script resource" do end it "should be a kind of Chef::Resource::WindowsScript" do - @resource.should be_a_kind_of(Chef::Resource) - @resource.should be_a_kind_of(Chef::Resource::WindowsScript) + expect(@resource).to be_a_kind_of(Chef::Resource) + expect(@resource).to be_a_kind_of(Chef::Resource::WindowsScript) end context "when evaluating guards" do it "should have a default_guard_interpreter attribute that is the same as the resource" do - @resource.default_guard_interpreter.should == @resource.resource_name + expect(@resource.default_guard_interpreter).to eq(@resource.resource_name) end it "should default to using guard_interpreter attribute that is the same as the resource" do - @resource.guard_interpreter.should == @resource.resource_name + expect(@resource.guard_interpreter).to eq(@resource.resource_name) end it "should use a resource to evaluate the guard when guard_interpreter is not specified" do - Chef::GuardInterpreter::ResourceGuardInterpreter.any_instance.should_receive(:evaluate_action).and_return(true) - Chef::GuardInterpreter::DefaultGuardInterpreter.any_instance.should_not_receive(:evaluate) + expect_any_instance_of(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:evaluate_action).and_return(true) + expect_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).not_to receive(:evaluate) @resource.only_if 'echo hi' - @resource.should_skip?(:run).should == nil + expect(@resource.should_skip?(:run)).to eq(nil) end describe "when the guard is given a ruby block" do it "should evaluate the guard if the guard_interpreter is set to its default value" do @resource.only_if { true } - @resource.should_skip?(:run).should == nil + expect(@resource.should_skip?(:run)).to eq(nil) end it "should raise an exception if the guard_interpreter is overridden from its default value" do diff --git a/spec/unit/api_client/registration_spec.rb b/spec/unit/api_client/registration_spec.rb index d752429676..55348ec8ee 100644 --- a/spec/unit/api_client/registration_spec.rb +++ b/spec/unit/api_client/registration_spec.rb @@ -85,7 +85,7 @@ describe Chef::ApiClient::Registration do before do Chef::Config[:validation_client_name] = "test-validator" Chef::Config[:validation_key] = File.expand_path('ssl/private_key.pem', CHEF_SPEC_DATA) - OpenSSL::PKey::RSA.stub(:generate).with(2048).and_return(generated_private_key) + allow(OpenSSL::PKey::RSA).to receive(:generate).with(2048).and_return(generated_private_key) end after do @@ -93,51 +93,51 @@ describe Chef::ApiClient::Registration do end it "has an HTTP client configured with validator credentials" do - registration.http_api.should be_a_kind_of(Chef::REST) - registration.http_api.client_name.should == "test-validator" - registration.http_api.signing_key.should == private_key_data + expect(registration.http_api).to be_a_kind_of(Chef::REST) + expect(registration.http_api.client_name).to eq("test-validator") + expect(registration.http_api.signing_key).to eq(private_key_data) end describe "when creating/updating the client on the server" do before do - registration.stub(:http_api).and_return(http_mock) + allow(registration).to receive(:http_api).and_return(http_mock) end it "posts a locally generated public key to the server to create a client" do - http_mock.should_receive(:post). + expect(http_mock).to receive(:post). with("clients", expected_post_data). and_return(create_with_pkey_response) - registration.create_or_update.should == create_with_pkey_response - registration.private_key.should == generated_private_key_pem + expect(registration.create_or_update).to eq(create_with_pkey_response) + expect(registration.private_key).to eq(generated_private_key_pem) end it "puts a locally generated public key to the server to update a client" do - http_mock.should_receive(:post). + expect(http_mock).to receive(:post). with("clients", expected_post_data). and_raise(exception_409) - http_mock.should_receive(:put). + expect(http_mock).to receive(:put). with("clients/#{client_name}", expected_put_data). and_return(update_with_pkey_response) - registration.create_or_update.should == update_with_pkey_response - registration.private_key.should == generated_private_key_pem + expect(registration.create_or_update).to eq(update_with_pkey_response) + expect(registration.private_key).to eq(generated_private_key_pem) end it "writes the generated private key to disk" do - http_mock.should_receive(:post). + expect(http_mock).to receive(:post). with("clients", expected_post_data). and_return(create_with_pkey_response) registration.run - IO.read(key_location).should == generated_private_key_pem + expect(IO.read(key_location)).to eq(generated_private_key_pem) end context "and the client already exists on a Chef 11 server" do it "requests a new key from the server and saves it" do - http_mock.should_receive(:post).and_raise(exception_409) - http_mock.should_receive(:put). + expect(http_mock).to receive(:post).and_raise(exception_409) + expect(http_mock).to receive(:put). with("clients/#{client_name}", expected_put_data). and_return(update_with_pkey_response) - registration.create_or_update.should == update_with_pkey_response - registration.private_key.should == generated_private_key_pem + expect(registration.create_or_update).to eq(update_with_pkey_response) + expect(registration.private_key).to eq(generated_private_key_pem) end end @@ -153,37 +153,37 @@ describe Chef::ApiClient::Registration do before do Chef::Config[:local_key_generation] = false - OpenSSL::PKey::RSA.should_not_receive(:generate) + expect(OpenSSL::PKey::RSA).not_to receive(:generate) end it "creates a new ApiClient on the server using the validator identity" do - http_mock.should_receive(:post). + expect(http_mock).to receive(:post). with("clients", expected_post_data). and_return(server_v10_response) - registration.create_or_update.should == server_v10_response - registration.private_key.should == "--begin rsa key etc--" + expect(registration.create_or_update).to eq(server_v10_response) + expect(registration.private_key).to eq("--begin rsa key etc--") end context "and the client already exists on a Chef 11 server" do it "requests a new key from the server and saves it" do - http_mock.should_receive(:post).and_raise(exception_409) - http_mock.should_receive(:put). + expect(http_mock).to receive(:post).and_raise(exception_409) + expect(http_mock).to receive(:put). with("clients/#{client_name}", expected_put_data). and_return(server_v11_response) - registration.create_or_update.should == server_v11_response - registration.private_key.should == "--begin rsa key etc--" + expect(registration.create_or_update).to eq(server_v11_response) + expect(registration.private_key).to eq("--begin rsa key etc--") end end context "and the client already exists on a Chef 10 server" do it "requests a new key from the server and saves it" do - http_mock.should_receive(:post).with("clients", expected_post_data). + expect(http_mock).to receive(:post).with("clients", expected_post_data). and_raise(exception_409) - http_mock.should_receive(:put). + expect(http_mock).to receive(:put). with("clients/#{client_name}", expected_put_data). and_return(server_v10_response) - registration.create_or_update.should == server_v10_response - registration.private_key.should == "--begin rsa key etc--" + expect(registration.create_or_update).to eq(server_v10_response) + expect(registration.private_key).to eq("--begin rsa key etc--") end end end @@ -191,60 +191,60 @@ describe Chef::ApiClient::Registration do describe "when writing the private key to disk" do before do - registration.stub(:private_key).and_return('--begin rsa key etc--') + allow(registration).to receive(:private_key).and_return('--begin rsa key etc--') end # Permission read via File.stat is busted on windows, though creating the # file with 0600 has the desired effect of giving access rights to the # owner only. A platform-specific functional test would be helpful. it "creates the file with 0600 permissions", :unix_only do - File.should_not exist(key_location) + expect(File).not_to exist(key_location) registration.write_key - File.should exist(key_location) + expect(File).to exist(key_location) stat = File.stat(key_location) - (stat.mode & 07777).should == 0600 + expect(stat.mode & 07777).to eq(0600) end it "writes the private key content to the file" do registration.write_key - IO.read(key_location).should == "--begin rsa key etc--" + expect(IO.read(key_location)).to eq("--begin rsa key etc--") end end describe "when registering a client" do before do - registration.stub(:http_api).and_return(http_mock) + allow(registration).to receive(:http_api).and_return(http_mock) end it "creates the client on the server and writes the key" do - http_mock.should_receive(:post).ordered.and_return(server_v10_response) + expect(http_mock).to receive(:post).ordered.and_return(server_v10_response) registration.run - IO.read(key_location).should == generated_private_key_pem + expect(IO.read(key_location)).to eq(generated_private_key_pem) end it "retries up to 5 times" do response_500 = Net::HTTPInternalServerError.new("1.1", "500", "Internal Server Error") exception_500 = Net::HTTPFatalError.new("500 Internal Server Error", response_500) - http_mock.should_receive(:post).ordered.and_raise(exception_500) # 1 - http_mock.should_receive(:post).ordered.and_raise(exception_500) # 2 - http_mock.should_receive(:post).ordered.and_raise(exception_500) # 3 - http_mock.should_receive(:post).ordered.and_raise(exception_500) # 4 - http_mock.should_receive(:post).ordered.and_raise(exception_500) # 5 + expect(http_mock).to receive(:post).ordered.and_raise(exception_500) # 1 + expect(http_mock).to receive(:post).ordered.and_raise(exception_500) # 2 + expect(http_mock).to receive(:post).ordered.and_raise(exception_500) # 3 + expect(http_mock).to receive(:post).ordered.and_raise(exception_500) # 4 + expect(http_mock).to receive(:post).ordered.and_raise(exception_500) # 5 - http_mock.should_receive(:post).ordered.and_return(server_v10_response) + expect(http_mock).to receive(:post).ordered.and_return(server_v10_response) registration.run - IO.read(key_location).should == generated_private_key_pem + expect(IO.read(key_location)).to eq(generated_private_key_pem) end it "gives up retrying after the max attempts" do response_500 = Net::HTTPInternalServerError.new("1.1", "500", "Internal Server Error") exception_500 = Net::HTTPFatalError.new("500 Internal Server Error", response_500) - http_mock.should_receive(:post).exactly(6).times.and_raise(exception_500) + expect(http_mock).to receive(:post).exactly(6).times.and_raise(exception_500) - lambda {registration.run}.should raise_error(Net::HTTPFatalError) + expect {registration.run}.to raise_error(Net::HTTPFatalError) end end diff --git a/spec/unit/api_client_spec.rb b/spec/unit/api_client_spec.rb index bd6c5ef7fd..7f8687e2b9 100644 --- a/spec/unit/api_client_spec.rb +++ b/spec/unit/api_client_spec.rb @@ -28,64 +28,64 @@ describe Chef::ApiClient do it "has a name attribute" do @client.name("ops_master") - @client.name.should == "ops_master" + expect(@client.name).to eq("ops_master") end it "does not allow spaces in the name" do - lambda { @client.name "ops master" }.should raise_error(ArgumentError) + expect { @client.name "ops master" }.to raise_error(ArgumentError) end it "only allows string values for the name" do - lambda { @client.name Hash.new }.should raise_error(ArgumentError) + expect { @client.name Hash.new }.to raise_error(ArgumentError) end it "has an admin flag attribute" do @client.admin(true) - @client.admin.should be_true + expect(@client.admin).to be_truthy end it "defaults to non-admin" do - @client.admin.should be_false + expect(@client.admin).to be_falsey end it "allows only boolean values for the admin flag" do - lambda { @client.admin(false) }.should_not raise_error - lambda { @client.admin(Hash.new) }.should raise_error(ArgumentError) + expect { @client.admin(false) }.not_to raise_error + expect { @client.admin(Hash.new) }.to raise_error(ArgumentError) end it "has a 'validator' flag attribute" do @client.validator(true) - @client.validator.should be_true + expect(@client.validator).to be_truthy end it "defaults to non-validator" do - @client.validator.should be_false + expect(@client.validator).to be_falsey end it "allows only boolean values for the 'validator' flag" do - lambda { @client.validator(false) }.should_not raise_error - lambda { @client.validator(Hash.new) }.should raise_error(ArgumentError) + expect { @client.validator(false) }.not_to raise_error + expect { @client.validator(Hash.new) }.to raise_error(ArgumentError) end it "has a public key attribute" do @client.public_key("super public") - @client.public_key.should == "super public" + expect(@client.public_key).to eq("super public") end it "accepts only String values for the public key" do - lambda { @client.public_key "" }.should_not raise_error - lambda { @client.public_key Hash.new }.should raise_error(ArgumentError) + expect { @client.public_key "" }.not_to raise_error + expect { @client.public_key Hash.new }.to raise_error(ArgumentError) end it "has a private key attribute" do @client.private_key("super private") - @client.private_key.should == "super private" + expect(@client.private_key).to eq("super private") end it "accepts only String values for the private key" do - lambda { @client.private_key "" }.should_not raise_error - lambda { @client.private_key Hash.new }.should raise_error(ArgumentError) + expect { @client.private_key "" }.not_to raise_error + expect { @client.private_key Hash.new }.to raise_error(ArgumentError) end describe "when serializing to JSON" do @@ -96,32 +96,32 @@ describe Chef::ApiClient do end it "serializes as a JSON object" do - @json.should match(/^\{.+\}$/) + expect(@json).to match(/^\{.+\}$/) end it "includes the name value" do - @json.should include(%q{"name":"black"}) + expect(@json).to include(%q{"name":"black"}) end it "includes the public key value" do - @json.should include(%{"public_key":"crowes"}) + expect(@json).to include(%{"public_key":"crowes"}) end it "includes the 'admin' flag" do - @json.should include(%q{"admin":false}) + expect(@json).to include(%q{"admin":false}) end it "includes the 'validator' flag" do - @json.should include(%q{"validator":false}) + expect(@json).to include(%q{"validator":false}) end it "includes the private key when present" do @client.private_key("monkeypants") - @client.to_json.should include(%q{"private_key":"monkeypants"}) + expect(@client.to_json).to include(%q{"private_key":"monkeypants"}) end it "does not include the private key if not present" do - @json.should_not include("private_key") + expect(@json).not_to include("private_key") end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -143,27 +143,27 @@ describe Chef::ApiClient do end it "should deserialize to a Chef::ApiClient object" do - @client.should be_a_kind_of(Chef::ApiClient) + expect(@client).to be_a_kind_of(Chef::ApiClient) end it "preserves the name" do - @client.name.should == "black" + expect(@client.name).to eq("black") end it "preserves the public key" do - @client.public_key.should == "crowes" + expect(@client.public_key).to eq("crowes") end it "preserves the admin status" do - @client.admin.should be_true + expect(@client.admin).to be_truthy end it "preserves the 'validator' status" do - @client.validator.should be_true + expect(@client.validator).to be_truthy end it "includes the private key if present" do - @client.private_key.should == "monkeypants" + expect(@client.private_key).to eq("monkeypants") end end @@ -183,33 +183,33 @@ describe Chef::ApiClient do "json_class" => "Chef::ApiClient" } @http_client = double("Chef::REST mock") - Chef::REST.stub(:new).and_return(@http_client) - @http_client.should_receive(:get).with("clients/black").and_return(client) + allow(Chef::REST).to receive(:new).and_return(@http_client) + expect(@http_client).to receive(:get).with("clients/black").and_return(client) @client = Chef::ApiClient.load(client['name']) end it "should deserialize to a Chef::ApiClient object" do - @client.should be_a_kind_of(Chef::ApiClient) + expect(@client).to be_a_kind_of(Chef::ApiClient) end it "preserves the name" do - @client.name.should == "black" + expect(@client.name).to eq("black") end it "preserves the public key" do - @client.public_key.should == "crowes" + expect(@client.public_key).to eq("crowes") end it "preserves the admin status" do - @client.admin.should be_a_kind_of(TrueClass) + expect(@client.admin).to be_a_kind_of(TrueClass) end it "preserves the 'validator' status" do - @client.validator.should be_a_kind_of(TrueClass) + expect(@client.validator).to be_a_kind_of(TrueClass) end it "includes the private key if present" do - @client.private_key.should == "monkeypants" + expect(@client.private_key).to eq("monkeypants") end end @@ -230,9 +230,9 @@ describe Chef::ApiClient do end it "has an HTTP client configured with default credentials" do - @client.http_api.should be_a_kind_of(Chef::REST) - @client.http_api.client_name.should == "silent-bob" - @client.http_api.signing_key.to_s.should == private_key_data + expect(@client.http_api).to be_a_kind_of(Chef::REST) + expect(@client.http_api.client_name).to eq("silent-bob") + expect(@client.http_api.signing_key.to_s).to eq(private_key_data) end end @@ -240,7 +240,7 @@ describe Chef::ApiClient do describe "when requesting a new key" do before do @http_client = double("Chef::REST mock") - Chef::REST.stub(:new).and_return(@http_client) + allow(Chef::REST).to receive(:new).and_return(@http_client) end context "and the client does not exist on the server" do @@ -248,11 +248,11 @@ describe Chef::ApiClient do @a_404_response = Net::HTTPNotFound.new("404 not found and such", nil, nil) @a_404_exception = Net::HTTPServerException.new("404 not found exception", @a_404_response) - @http_client.should_receive(:get).with("clients/lost-my-key").and_raise(@a_404_exception) + expect(@http_client).to receive(:get).with("clients/lost-my-key").and_raise(@a_404_exception) end it "raises a 404 error" do - lambda { Chef::ApiClient.reregister("lost-my-key") }.should raise_error(Net::HTTPServerException) + expect { Chef::ApiClient.reregister("lost-my-key") }.to raise_error(Net::HTTPServerException) end end @@ -260,7 +260,7 @@ describe Chef::ApiClient do before do @api_client_without_key = Chef::ApiClient.new @api_client_without_key.name("lost-my-key") - @http_client.should_receive(:get).with("clients/lost-my-key").and_return(@api_client_without_key) + expect(@http_client).to receive(:get).with("clients/lost-my-key").and_return(@api_client_without_key) end @@ -269,7 +269,7 @@ describe Chef::ApiClient do @api_client_with_key = Chef::ApiClient.new @api_client_with_key.name("lost-my-key") @api_client_with_key.private_key("the new private key") - @http_client.should_receive(:put). + expect(@http_client).to receive(:put). with("clients/lost-my-key", :name => "lost-my-key", :admin => false, :validator => false, :private_key => true). and_return(@api_client_with_key) end @@ -277,17 +277,17 @@ describe Chef::ApiClient do it "returns an ApiClient with a private key" do response = Chef::ApiClient.reregister("lost-my-key") # no sane == method for ApiClient :'( - response.should == @api_client_without_key - response.private_key.should == "the new private key" - response.name.should == "lost-my-key" - response.admin.should be_false + expect(response).to eq(@api_client_without_key) + expect(response.private_key).to eq("the new private key") + expect(response.name).to eq("lost-my-key") + expect(response.admin).to be_falsey end end context "and the client exists on a Chef 10-like server" do before do @api_client_with_key = {"name" => "lost-my-key", "private_key" => "the new private key"} - @http_client.should_receive(:put). + expect(@http_client).to receive(:put). with("clients/lost-my-key", :name => "lost-my-key", :admin => false, :validator => false, :private_key => true). and_return(@api_client_with_key) end @@ -295,11 +295,11 @@ describe Chef::ApiClient do it "returns an ApiClient with a private key" do response = Chef::ApiClient.reregister("lost-my-key") # no sane == method for ApiClient :'( - response.should == @api_client_without_key - response.private_key.should == "the new private key" - response.name.should == "lost-my-key" - response.admin.should be_false - response.validator.should be_false + expect(response).to eq(@api_client_without_key) + expect(response.private_key).to eq("the new private key") + expect(response.name).to eq("lost-my-key") + expect(response.admin).to be_falsey + expect(response.validator).to be_falsey end end diff --git a/spec/unit/application/apply_spec.rb b/spec/unit/application/apply_spec.rb index e29c038340..5a6366281f 100644 --- a/spec/unit/application/apply_spec.rb +++ b/spec/unit/application/apply_spec.rb @@ -21,7 +21,7 @@ describe Chef::Application::Apply do before do @app = Chef::Application::Apply.new - @app.stub(:configure_logging).and_return(true) + allow(@app).to receive(:configure_logging).and_return(true) @recipe_text = "package 'nyancat'" Chef::Config[:solo] = true end @@ -29,7 +29,7 @@ describe Chef::Application::Apply do describe "configuring the application" do it "should set solo mode to true" do @app.reconfigure - Chef::Config[:solo].should be_true + expect(Chef::Config[:solo]).to be_truthy end end describe "read_recipe_file" do @@ -37,30 +37,30 @@ describe Chef::Application::Apply do @recipe_file_name = "foo.rb" @recipe_path = File.expand_path(@recipe_file_name) @recipe_file = double("Tempfile (mock)", :read => @recipe_text) - @app.stub(:open).with(@recipe_path).and_return(@recipe_file) - File.stub(:exist?).with(@recipe_path).and_return(true) - Chef::Application.stub(:fatal!).and_return(true) + allow(@app).to receive(:open).with(@recipe_path).and_return(@recipe_file) + allow(File).to receive(:exist?).with(@recipe_path).and_return(true) + allow(Chef::Application).to receive(:fatal!).and_return(true) end it "should read text properly" do - @app.read_recipe_file(@recipe_file_name)[0].should == @recipe_text + expect(@app.read_recipe_file(@recipe_file_name)[0]).to eq(@recipe_text) end it "should return a file_handle" do - @app.read_recipe_file(@recipe_file_name)[1].should be_instance_of(RSpec::Mocks::Mock) + expect(@app.read_recipe_file(@recipe_file_name)[1]).to be_instance_of(RSpec::Mocks::Double) end describe "when recipe is nil" do it "should raise a fatal with the missing filename message" do - Chef::Application.should_receive(:fatal!).with("No recipe file was provided", 1) + expect(Chef::Application).to receive(:fatal!).with("No recipe file was provided", 1) @app.read_recipe_file(nil) end end describe "when recipe doesn't exist" do before do - File.stub(:exist?).with(@recipe_path).and_return(false) + allow(File).to receive(:exist?).with(@recipe_path).and_return(false) end it "should raise a fatal with the file doesn't exist message" do - Chef::Application.should_receive(:fatal!).with(/^No file exists at/, 1) + expect(Chef::Application).to receive(:fatal!).with(/^No file exists at/, 1) @app.read_recipe_file(@recipe_file_name) end end @@ -72,13 +72,13 @@ describe Chef::Application::Apply do @recipe_fh = @app.instance_variable_get(:@recipe_fh) end it "should open a tempfile" do - @recipe_fh.path.should match(/.*recipe-temporary-file.*/) + expect(@recipe_fh.path).to match(/.*recipe-temporary-file.*/) end it "should write recipe text to the tempfile" do - @recipe_fh.read.should == @recipe_text + expect(@recipe_fh.read).to eq(@recipe_text) end it "should save the filename for later use" do - @recipe_fh.path.should == @app.instance_variable_get(:@recipe_filename) + expect(@recipe_fh.path).to eq(@app.instance_variable_get(:@recipe_filename)) end end describe "recipe_file_arg" do @@ -86,8 +86,8 @@ describe Chef::Application::Apply do ARGV.clear end it "should exit and log message" do - Chef::Log.should_receive(:debug).with(/^No recipe file provided/) - lambda { @app.run }.should raise_error(SystemExit) { |e| e.status.should == 1 } + expect(Chef::Log).to receive(:debug).with(/^No recipe file provided/) + expect { @app.run }.to raise_error(SystemExit) { |e| expect(e.status).to eq(1) } end end diff --git a/spec/unit/application/client_spec.rb b/spec/unit/application/client_spec.rb index ee91e67256..38e051e269 100644 --- a/spec/unit/application/client_spec.rb +++ b/spec/unit/application/client_spec.rb @@ -19,16 +19,16 @@ require 'spec_helper' describe Chef::Application::Client, "reconfigure" do before do - Kernel.stub(:trap).and_return(:ok) + allow(Kernel).to receive(:trap).and_return(:ok) @original_argv = ARGV.dup ARGV.clear @app = Chef::Application::Client.new - @app.stub(:trap) - @app.stub(:configure_opt_parser).and_return(true) - @app.stub(:configure_chef).and_return(true) - @app.stub(:configure_logging).and_return(true) + allow(@app).to receive(:trap) + allow(@app).to receive(:configure_opt_parser).and_return(true) + allow(@app).to receive(:configure_chef).and_return(true) + allow(@app).to receive(:configure_logging).and_return(true) @app.cli_arguments = [] Chef::Config[:interval] = 10 @@ -53,7 +53,7 @@ describe Chef::Application::Client, "reconfigure" do end it "should terminate with message" do - Chef::Application.should_receive(:fatal!).with( + expect(Chef::Application).to receive(:fatal!).with( "Unforked chef-client interval runs are disabled in Chef 12. Configuration settings: interval = 600 seconds @@ -71,7 +71,7 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config it "should reconfigure chef-client" do @app.reconfigure - Chef::Config[:interval].should be_nil + expect(Chef::Config[:interval]).to be_nil end end end @@ -84,7 +84,7 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config it "should set the interval to 1800" do @app.reconfigure - Chef::Config.interval.should == 1800 + expect(Chef::Config.interval).to eq(1800) end end @@ -98,12 +98,12 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config it "ignores the splay" do @app.reconfigure - Chef::Config.splay.should be_nil + expect(Chef::Config.splay).to be_nil end it "forces the interval to nil" do @app.reconfigure - Chef::Config.interval.should be_nil + expect(Chef::Config.interval).to be_nil end end @@ -116,13 +116,13 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config before do Chef::Config[:json_attribs] = json_source - Chef::ConfigFetcher.should_receive(:new).with(json_source). + expect(Chef::ConfigFetcher).to receive(:new).with(json_source). and_return(config_fetcher) end it "reads the JSON attributes from the specified source" do @app.reconfigure - @app.chef_client_json.should == json_attribs + expect(@app.chef_client_json).to eq(json_attribs) end end end @@ -131,13 +131,13 @@ describe Chef::Application::Client, "setup_application" do before do @app = Chef::Application::Client.new # this is all stuff the reconfigure method needs - @app.stub(:configure_opt_parser).and_return(true) - @app.stub(:configure_chef).and_return(true) - @app.stub(:configure_logging).and_return(true) + allow(@app).to receive(:configure_opt_parser).and_return(true) + allow(@app).to receive(:configure_chef).and_return(true) + allow(@app).to receive(:configure_logging).and_return(true) end it "should change privileges" do - Chef::Daemon.should_receive(:change_privilege).and_return(true) + expect(Chef::Daemon).to receive(:change_privilege).and_return(true) @app.setup_application end after do @@ -159,9 +159,9 @@ describe Chef::Application::Client, "configure_chef" do it "should set the colored output to false by default on windows and true otherwise" do if windows? - Chef::Config[:color].should be_false + expect(Chef::Config[:color]).to be_falsey else - Chef::Config[:color].should be_true + expect(Chef::Config[:color]).to be_truthy end end end @@ -177,8 +177,8 @@ describe Chef::Application::Client, "run_application", :unix_only do @pipe = IO.pipe @client = Chef::Client.new - Chef::Client.stub(:new).and_return(@client) - @client.stub(:run) do + allow(Chef::Client).to receive(:new).and_return(@client) + allow(@client).to receive(:run) do @pipe[1].puts 'started' sleep 1 @pipe[1].puts 'finished' @@ -189,7 +189,7 @@ describe Chef::Application::Client, "run_application", :unix_only do context "when converging in forked process" do before do Chef::Config[:daemonize] = true - Chef::Daemon.stub(:daemonize).and_return(true) + allow(Chef::Daemon).to receive(:daemonize).and_return(true) end it "should exit hard with exitstatus 3" do @@ -198,19 +198,19 @@ describe Chef::Application::Client, "run_application", :unix_only do end Process.kill("TERM", pid) _pid, result = Process.waitpid2(pid) - result.exitstatus.should == 3 + expect(result.exitstatus).to eq(3) end it "should allow child to finish converging" do pid = fork do @app.run_application end - @pipe[0].gets.should == "started\n" + expect(@pipe[0].gets).to eq("started\n") Process.kill("TERM", pid) Process.wait sleep 1 # Make sure we give the converging child process enough time to finish - IO.select([@pipe[0]], nil, nil, 0).should_not be_nil - @pipe[0].gets.should == "finished\n" + expect(IO.select([@pipe[0]], nil, nil, 0)).not_to be_nil + expect(@pipe[0].gets).to eq("finished\n") end end @@ -224,12 +224,12 @@ describe Chef::Application::Client, "run_application", :unix_only do pid = fork do @app.run_application end - @pipe[0].gets.should == "started\n" + expect(@pipe[0].gets).to eq("started\n") Process.kill("TERM", pid) _pid, result = Process.waitpid2(pid) - result.exitstatus.should == 0 - IO.select([@pipe[0]], nil, nil, 0).should_not be_nil - @pipe[0].gets.should == "finished\n" + expect(result.exitstatus).to eq(0) + expect(IO.select([@pipe[0]], nil, nil, 0)).not_to be_nil + expect(@pipe[0].gets).to eq("finished\n") end it "should exit hard when sent before converge" do @@ -239,7 +239,7 @@ describe Chef::Application::Client, "run_application", :unix_only do end Process.kill("TERM", pid) _pid, result = Process.waitpid2(pid) - result.exitstatus.should == 3 + expect(result.exitstatus).to eq(3) end end end @@ -255,7 +255,7 @@ describe Chef::Application::Client, "run_application", :unix_only do # Chef::Log.init($stderr) # Chef::Log.level = :debug - @app.stub(:run_chef_client) do + allow(@app).to receive(:run_chef_client) do run_count += 1 if run_count > 3 @@ -277,7 +277,7 @@ describe Chef::Application::Client, "run_application", :unix_only do # We have to do it this way because the main loop of # Chef::Application::Client swallows most exceptions, and we need to be # able to expose our expectation failures to the parent process in the test. - @app.stub(:interval_sleep) do |arg| + allow(@app).to receive(:interval_sleep) do |arg| number_of_sleep_calls += 1 if number_of_sleep_calls > 1 exit 127 @@ -286,12 +286,12 @@ describe Chef::Application::Client, "run_application", :unix_only do end it "shouldn't sleep when sent USR1" do - @app.stub(:interval_sleep).with(0).and_call_original + allow(@app).to receive(:interval_sleep).with(0).and_call_original pid = fork do @app.run_application end _pid, result = Process.waitpid2(pid) - result.exitstatus.should == 0 + expect(result.exitstatus).to eq(0) end end end diff --git a/spec/unit/application/knife_spec.rb b/spec/unit/application/knife_spec.rb index 0933d7e178..806a596a61 100644 --- a/spec/unit/application/knife_spec.rb +++ b/spec/unit/application/knife_spec.rb @@ -35,66 +35,66 @@ describe Chef::Application::Knife do before(:each) do # Prevent code from getting loaded on every test invocation. - Chef::Knife.stub(:load_commands) + allow(Chef::Knife).to receive(:load_commands) @knife = Chef::Application::Knife.new - @knife.stub(:puts) - @knife.stub(:trap) - Chef::Knife.stub(:list_commands) + allow(@knife).to receive(:puts) + allow(@knife).to receive(:trap) + allow(Chef::Knife).to receive(:list_commands) end it "should exit 1 and print the options if no arguments are given at all" do with_argv([]) do - lambda { @knife.run }.should raise_error(SystemExit) { |e| e.status.should == 1 } + expect { @knife.run }.to raise_error(SystemExit) { |e| expect(e.status).to eq(1) } end end it "should exit 2 if run without a sub command" do with_argv("--user", "adam") do - Chef::Log.should_receive(:error).with(/you need to pass a sub\-command/i) - lambda { @knife.run }.should raise_error(SystemExit) { |e| e.status.should == 2 } + expect(Chef::Log).to receive(:error).with(/you need to pass a sub\-command/i) + expect { @knife.run }.to raise_error(SystemExit) { |e| expect(e.status).to eq(2) } end end it "should run a sub command with the applications command line option prototype" do with_argv(*%w{noop knife command with some args}) do knife = double(Chef::Knife) - Chef::Knife.should_receive(:run).with(ARGV, @knife.options).and_return(knife) - @knife.should_receive(:exit).with(0) + expect(Chef::Knife).to receive(:run).with(ARGV, @knife.options).and_return(knife) + expect(@knife).to receive(:exit).with(0) @knife.run end end it "should set the colored output to false by default on windows and true otherwise" do with_argv(*%w{noop knife command}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end if windows? - Chef::Config[:color].should be_false + expect(Chef::Config[:color]).to be_falsey else - Chef::Config[:color].should be_true + expect(Chef::Config[:color]).to be_truthy end end describe "when given a path to the client key" do it "expands a relative path relative to the CWD" do relative_path = '.chef/client.pem' - Dir.stub(:pwd).and_return(CHEF_SPEC_DATA) + allow(Dir).to receive(:pwd).and_return(CHEF_SPEC_DATA) with_argv(*%W{noop knife command -k #{relative_path}}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:client_key].should == File.join(CHEF_SPEC_DATA, relative_path) + expect(Chef::Config[:client_key]).to eq(File.join(CHEF_SPEC_DATA, relative_path)) end it "expands a ~/home/path to the correct full path" do home_path = '~/.chef/client.pem' with_argv(*%W{noop knife command -k #{home_path}}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:client_key].should == File.join(ENV['HOME'], '.chef/client.pem').gsub((File::ALT_SEPARATOR || '\\'), File::SEPARATOR) + expect(Chef::Config[:client_key]).to eq(File.join(ENV['HOME'], '.chef/client.pem').gsub((File::ALT_SEPARATOR || '\\'), File::SEPARATOR)) end it "does not expand a full path" do @@ -104,10 +104,10 @@ describe Chef::Application::Knife do '/etc/chef/client.pem' end with_argv(*%W{noop knife command -k #{full_path}}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:client_key].should == full_path + expect(Chef::Config[:client_key]).to eq(full_path) end end @@ -119,52 +119,52 @@ describe Chef::Application::Knife do it "should default to no environment" do with_argv(*%w{noop knife command}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:environment].should == nil + expect(Chef::Config[:environment]).to eq(nil) end it "should load the environment from the config file" do config_file = File.join(CHEF_SPEC_DATA,"environment-config.rb") with_argv(*%W{noop knife command -c #{config_file}}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:environment].should == 'production' + expect(Chef::Config[:environment]).to eq('production') end it "should load the environment from the CLI options" do with_argv(*%W{noop knife command -E development}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:environment].should == 'development' + expect(Chef::Config[:environment]).to eq('development') end it "should override the config file environment with the CLI environment" do config_file = File.join(CHEF_SPEC_DATA,"environment-config.rb") with_argv(*%W{noop knife command -c #{config_file} -E override}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:environment].should == 'override' + expect(Chef::Config[:environment]).to eq('override') end it "should override the config file environment with the CLI environment regardless of order" do config_file = File.join(CHEF_SPEC_DATA,"environment-config.rb") with_argv(*%W{noop knife command -E override -c #{config_file}}) do - @knife.should_receive(:exit).with(0) + expect(@knife).to receive(:exit).with(0) @knife.run end - Chef::Config[:environment].should == 'override' + expect(Chef::Config[:environment]).to eq('override') end it "should run a sub command with the applications command line option prototype" do with_argv(*%w{noop knife command with some args}) do knife = double(Chef::Knife) - Chef::Knife.should_receive(:run).with(ARGV, @knife.options).and_return(knife) - @knife.should_receive(:exit).with(0) + expect(Chef::Knife).to receive(:run).with(ARGV, @knife.options).and_return(knife) + expect(@knife).to receive(:exit).with(0) @knife.run end end diff --git a/spec/unit/application/solo_spec.rb b/spec/unit/application/solo_spec.rb index e29fcc9367..26d7d34caa 100644 --- a/spec/unit/application/solo_spec.rb +++ b/spec/unit/application/solo_spec.rb @@ -19,12 +19,12 @@ require 'spec_helper' describe Chef::Application::Solo do before do - Kernel.stub(:trap).and_return(:ok) + allow(Kernel).to receive(:trap).and_return(:ok) @app = Chef::Application::Solo.new - @app.stub(:configure_opt_parser).and_return(true) - @app.stub(:configure_chef).and_return(true) - @app.stub(:configure_logging).and_return(true) - @app.stub(:trap) + allow(@app).to receive(:configure_opt_parser).and_return(true) + allow(@app).to receive(:configure_chef).and_return(true) + allow(@app).to receive(:configure_logging).and_return(true) + allow(@app).to receive(:trap) Chef::Config[:recipe_url] = false Chef::Config[:json_attribs] = false Chef::Config[:solo] = true @@ -33,7 +33,7 @@ describe Chef::Application::Solo do describe "configuring the application" do it "should set solo mode to true" do @app.reconfigure - Chef::Config[:solo].should be_true + expect(Chef::Config[:solo]).to be_truthy end describe "when configured to not fork the client process" do @@ -50,7 +50,7 @@ describe Chef::Application::Solo do end it "should terminate with message" do - Chef::Application.should_receive(:fatal!).with( + expect(Chef::Application).to receive(:fatal!).with( "Unforked chef-client interval runs are disabled in Chef 12. Configuration settings: interval = 600 seconds @@ -69,7 +69,7 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config it "should set the interval to 1800" do Chef::Config[:interval] = nil @app.reconfigure - Chef::Config[:interval].should == 1800 + expect(Chef::Config[:interval]).to eq(1800) end end @@ -80,13 +80,13 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config before do Chef::Config[:json_attribs] = json_source - Chef::ConfigFetcher.should_receive(:new).with(json_source). + expect(Chef::ConfigFetcher).to receive(:new).with(json_source). and_return(config_fetcher) end it "reads the JSON attributes from the specified source" do @app.reconfigure - @app.chef_client_json.should == json_attribs + expect(@app.chef_client_json).to eq(json_attribs) end end @@ -94,33 +94,33 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config before do Chef::Config[:cookbook_path] = "#{Dir.tmpdir}/chef-solo/cookbooks" Chef::Config[:recipe_url] = "http://junglist.gen.nz/recipes.tgz" - FileUtils.stub(:mkdir_p).and_return(true) + allow(FileUtils).to receive(:mkdir_p).and_return(true) @tarfile = StringIO.new("remote_tarball_content") - @app.stub(:open).with("http://junglist.gen.nz/recipes.tgz").and_yield(@tarfile) + allow(@app).to receive(:open).with("http://junglist.gen.nz/recipes.tgz").and_yield(@tarfile) @target_file = StringIO.new - File.stub(:open).with("#{Dir.tmpdir}/chef-solo/recipes.tgz", "wb").and_yield(@target_file) + allow(File).to receive(:open).with("#{Dir.tmpdir}/chef-solo/recipes.tgz", "wb").and_yield(@target_file) - Chef::Mixin::Command.stub(:run_command).and_return(true) + allow(Chef::Mixin::Command).to receive(:run_command).and_return(true) end it "should create the recipes path based on the parent of the cookbook path" do - FileUtils.should_receive(:mkdir_p).with("#{Dir.tmpdir}/chef-solo").and_return(true) + expect(FileUtils).to receive(:mkdir_p).with("#{Dir.tmpdir}/chef-solo").and_return(true) @app.reconfigure end it "should download the recipes" do - @app.should_receive(:open).with("http://junglist.gen.nz/recipes.tgz").and_yield(@tarfile) + expect(@app).to receive(:open).with("http://junglist.gen.nz/recipes.tgz").and_yield(@tarfile) @app.reconfigure end it "should write the recipes to the target path" do @app.reconfigure - @target_file.string.should == "remote_tarball_content" + expect(@target_file.string).to eq("remote_tarball_content") end it "should untar the target file to the parent of the cookbook path" do - Chef::Mixin::Command.should_receive(:run_command).with({:command => "tar zxvf #{Dir.tmpdir}/chef-solo/recipes.tgz -C #{Dir.tmpdir}/chef-solo"}).and_return(true) + expect(Chef::Mixin::Command).to receive(:run_command).with({:command => "tar zxvf #{Dir.tmpdir}/chef-solo/recipes.tgz -C #{Dir.tmpdir}/chef-solo"}).and_return(true) @app.reconfigure end end @@ -135,13 +135,13 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config Chef::Config[:json_attribs] = json_source Chef::Config[:recipe_url] = "http://icanhas.cheezburger.com/lolcats" Chef::Config[:cookbook_path] = "#{Dir.tmpdir}/chef-solo/cookbooks" - FileUtils.stub(:mkdir_p).and_return(true) - Chef::Mixin::Command.stub(:run_command).and_return(true) + allow(FileUtils).to receive(:mkdir_p).and_return(true) + allow(Chef::Mixin::Command).to receive(:run_command).and_return(true) end it "should fetch the recipe_url first" do - @app.should_receive(:fetch_recipe_tarball).ordered - Chef::ConfigFetcher.should_receive(:new).ordered.and_return(config_fetcher) + expect(@app).to receive(:fetch_recipe_tarball).ordered + expect(Chef::ConfigFetcher).to receive(:new).ordered.and_return(config_fetcher) @app.reconfigure end end @@ -150,18 +150,18 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config before do Chef::Config[:solo] = true - Chef::Daemon.stub(:change_privilege) + allow(Chef::Daemon).to receive(:change_privilege) @chef_client = double("Chef::Client") - Chef::Client.stub(:new).and_return(@chef_client) + allow(Chef::Client).to receive(:new).and_return(@chef_client) @app = Chef::Application::Solo.new # this is all stuff the reconfigure method needs - @app.stub(:configure_opt_parser).and_return(true) - @app.stub(:configure_chef).and_return(true) - @app.stub(:configure_logging).and_return(true) + allow(@app).to receive(:configure_opt_parser).and_return(true) + allow(@app).to receive(:configure_chef).and_return(true) + allow(@app).to receive(:configure_logging).and_return(true) end it "should change privileges" do - Chef::Daemon.should_receive(:change_privilege).and_return(true) + expect(Chef::Daemon).to receive(:change_privilege).and_return(true) @app.setup_application end end diff --git a/spec/unit/application_spec.rb b/spec/unit/application_spec.rb index b7b69c6993..210f875fbe 100644 --- a/spec/unit/application_spec.rb +++ b/spec/unit/application_spec.rb @@ -24,9 +24,9 @@ describe Chef::Application do ARGV.clear Chef::Log.logger = Logger.new(StringIO.new) @app = Chef::Application.new - @app.stub(:trap) - Dir.stub(:chdir).and_return(0) - @app.stub(:reconfigure) + allow(@app).to receive(:trap) + allow(Dir).to receive(:chdir).and_return(0) + allow(@app).to receive(:reconfigure) Chef::Log.init(STDERR) end @@ -37,23 +37,23 @@ describe Chef::Application do describe "reconfigure" do before do @app = Chef::Application.new - @app.stub(:configure_chef).and_return(true) - @app.stub(:configure_logging).and_return(true) - @app.stub(:configure_proxy_environment_variables).and_return(true) + allow(@app).to receive(:configure_chef).and_return(true) + allow(@app).to receive(:configure_logging).and_return(true) + allow(@app).to receive(:configure_proxy_environment_variables).and_return(true) end it "should configure chef" do - @app.should_receive(:configure_chef).and_return(true) + expect(@app).to receive(:configure_chef).and_return(true) @app.reconfigure end it "should configure logging" do - @app.should_receive(:configure_logging).and_return(true) + expect(@app).to receive(:configure_logging).and_return(true) @app.reconfigure end it "should configure environment variables" do - @app.should_receive(:configure_proxy_environment_variables).and_return(true) + expect(@app).to receive(:configure_proxy_environment_variables).and_return(true) @app.reconfigure end end @@ -65,24 +65,24 @@ describe Chef::Application do describe "run" do before do - @app.stub(:setup_application).and_return(true) - @app.stub(:run_application).and_return(true) - @app.stub(:configure_chef).and_return(true) - @app.stub(:configure_logging).and_return(true) + allow(@app).to receive(:setup_application).and_return(true) + allow(@app).to receive(:run_application).and_return(true) + allow(@app).to receive(:configure_chef).and_return(true) + allow(@app).to receive(:configure_logging).and_return(true) end it "should reconfigure the application before running" do - @app.should_receive(:reconfigure).and_return(true) + expect(@app).to receive(:reconfigure).and_return(true) @app.run end it "should setup the application before running it" do - @app.should_receive(:setup_application).and_return(true) + expect(@app).to receive(:setup_application).and_return(true) @app.run end it "should run the actual application" do - @app.should_receive(:run_application).and_return(true) + expect(@app).to receive(:run_application).and_return(true) @app.run end end @@ -91,15 +91,15 @@ describe Chef::Application do describe "configure_chef" do before do # Silence warnings when no config file exists - Chef::Log.stub(:warn) + allow(Chef::Log).to receive(:warn) @app = Chef::Application.new #Chef::Config.stub(:merge!).and_return(true) - @app.stub(:parse_options).and_return(true) + allow(@app).to receive(:parse_options).and_return(true) end it "should parse the commandline options" do - @app.should_receive(:parse_options).and_return(true) + expect(@app).to receive(:parse_options).and_return(true) @app.config[:config_file] = "/etc/chef/default.rb" #have a config file set, to prevent triggering error block @app.configure_chef end @@ -110,7 +110,7 @@ describe Chef::Application do let(:config_location_pathname) do p = Pathname.new(config_location) - p.stub(:realpath).and_return(config_location) + allow(p).to receive(:realpath).and_return(config_location) p end @@ -119,21 +119,21 @@ describe Chef::Application do # force let binding to get evaluated or else we stub Pathname.new before we try to use it. config_location_pathname - Pathname.stub(:new).with(config_location).and_return(config_location_pathname) - File.should_receive(:read). + allow(Pathname).to receive(:new).with(config_location).and_return(config_location_pathname) + expect(File).to receive(:read). with(config_location). and_return(config_content) end it "should configure chef::config from a file" do - Chef::Config.should_receive(:from_string).with(config_content, config_location) + expect(Chef::Config).to receive(:from_string).with(config_content, config_location) @app.configure_chef end it "should merge the local config hash into chef::config" do #File.should_receive(:open).with("/etc/chef/default.rb").and_yield(@config_file) @app.configure_chef - Chef::Config.rspec_ran.should == "true" + expect(Chef::Config.rspec_ran).to eq("true") end end @@ -144,8 +144,8 @@ describe Chef::Application do end it "should emit a warning" do - Chef::Config.should_not_receive(:from_file).with("/etc/chef/default.rb") - Chef::Log.should_receive(:warn).with("No config file found or specified on command line, using command line options.") + expect(Chef::Config).not_to receive(:from_file).with("/etc/chef/default.rb") + expect(Chef::Log).to receive(:warn).with("No config file found or specified on command line, using command line options.") @app.configure_chef end end @@ -155,7 +155,7 @@ describe Chef::Application do @app.config[:config_file] = "/etc/chef/notfound" end it "should use the passed in command line options and defaults" do - Chef::Config.should_receive(:merge!) + expect(Chef::Config).to receive(:merge!) @app.configure_chef end end @@ -164,33 +164,33 @@ describe Chef::Application do describe "when configuring the logger" do before do @app = Chef::Application.new - Chef::Log.stub(:init) + allow(Chef::Log).to receive(:init) end it "should initialise the chef logger" do - Chef::Log.stub(:level=) + allow(Chef::Log).to receive(:level=) @monologger = double("Monologger") - MonoLogger.should_receive(:new).with(Chef::Config[:log_location]).and_return(@monologger) - Chef::Log.should_receive(:init).with(@monologger) + expect(MonoLogger).to receive(:new).with(Chef::Config[:log_location]).and_return(@monologger) + expect(Chef::Log).to receive(:init).with(@monologger) @app.configure_logging end it "should raise fatals if log location is invalid" do Chef::Config[:log_location] = "/tmp/non-existing-dir/logfile" - Chef::Log.should_receive(:fatal).at_least(:once) - Process.should_receive(:exit) + expect(Chef::Log).to receive(:fatal).at_least(:once) + expect(Process).to receive(:exit) @app.configure_logging end shared_examples_for "log_level_is_auto" do context "when STDOUT is to a tty" do before do - STDOUT.stub(:tty?).and_return(true) + allow(STDOUT).to receive(:tty?).and_return(true) end it "configures the log level to :warn" do @app.configure_logging - Chef::Log.level.should == :warn + expect(Chef::Log.level).to eq(:warn) end context "when force_logger is configured" do @@ -200,19 +200,19 @@ describe Chef::Application do it "configures the log level to info" do @app.configure_logging - Chef::Log.level.should == :info + expect(Chef::Log.level).to eq(:info) end end end context "when STDOUT is not to a tty" do before do - STDOUT.stub(:tty?).and_return(false) + allow(STDOUT).to receive(:tty?).and_return(false) end it "configures the log level to :info" do @app.configure_logging - Chef::Log.level.should == :info + expect(Chef::Log.level).to eq(:info) end context "when force_formatter is configured" do @@ -221,7 +221,7 @@ describe Chef::Application do end it "sets the log level to :warn" do @app.configure_logging - Chef::Log.level.should == :warn + expect(Chef::Log.level).to eq(:warn) end end end @@ -242,10 +242,10 @@ describe Chef::Application do describe "when configuring environment variables" do def configure_proxy_environment_variables_stubs - @app.stub(:configure_http_proxy).and_return(true) - @app.stub(:configure_https_proxy).and_return(true) - @app.stub(:configure_ftp_proxy).and_return(true) - @app.stub(:configure_no_proxy).and_return(true) + allow(@app).to receive(:configure_http_proxy).and_return(true) + allow(@app).to receive(:configure_https_proxy).and_return(true) + allow(@app).to receive(:configure_ftp_proxy).and_return(true) + allow(@app).to receive(:configure_no_proxy).and_return(true) end shared_examples_for "setting ENV['http_proxy']" do @@ -255,12 +255,12 @@ describe Chef::Application do it "should set ENV['http_proxy']" do @app.configure_proxy_environment_variables - @env['http_proxy'].should == "#{scheme}://#{address}:#{port}" + expect(@env['http_proxy']).to eq("#{scheme}://#{address}:#{port}") end it "should set ENV['HTTP_PROXY']" do @app.configure_proxy_environment_variables - @env['HTTP_PROXY'].should == "#{scheme}://#{address}:#{port}" + expect(@env['HTTP_PROXY']).to eq("#{scheme}://#{address}:#{port}") end describe "when Chef::Config[:http_proxy_user] is set" do @@ -270,8 +270,8 @@ describe Chef::Application do it "should set ENV['http_proxy'] with the username" do @app.configure_proxy_environment_variables - @env['http_proxy'].should == "#{scheme}://username@#{address}:#{port}" - @env['HTTP_PROXY'].should == "#{scheme}://username@#{address}:#{port}" + expect(@env['http_proxy']).to eq("#{scheme}://username@#{address}:#{port}") + expect(@env['HTTP_PROXY']).to eq("#{scheme}://username@#{address}:#{port}") end context "when :http_proxy_user contains '@' and/or ':'" do @@ -281,8 +281,8 @@ describe Chef::Application do it "should set ENV['http_proxy'] with the escaped username" do @app.configure_proxy_environment_variables - @env['http_proxy'].should == "#{scheme}://my%3Ausern%40me@#{address}:#{port}" - @env['HTTP_PROXY'].should == "#{scheme}://my%3Ausern%40me@#{address}:#{port}" + expect(@env['http_proxy']).to eq("#{scheme}://my%3Ausern%40me@#{address}:#{port}") + expect(@env['HTTP_PROXY']).to eq("#{scheme}://my%3Ausern%40me@#{address}:#{port}") end end @@ -293,8 +293,8 @@ describe Chef::Application do it "should set ENV['http_proxy'] with the password" do @app.configure_proxy_environment_variables - @env['http_proxy'].should == "#{scheme}://username:password@#{address}:#{port}" - @env['HTTP_PROXY'].should == "#{scheme}://username:password@#{address}:#{port}" + expect(@env['http_proxy']).to eq("#{scheme}://username:password@#{address}:#{port}") + expect(@env['HTTP_PROXY']).to eq("#{scheme}://username:password@#{address}:#{port}") end context "when :http_proxy_pass contains '@' and/or ':'" do @@ -304,8 +304,8 @@ describe Chef::Application do it "should set ENV['http_proxy'] with the escaped password" do @app.configure_proxy_environment_variables - @env['http_proxy'].should == "#{scheme}://username:%3AP%40ssword101@#{address}:#{port}" - @env['HTTP_PROXY'].should == "#{scheme}://username:%3AP%40ssword101@#{address}:#{port}" + expect(@env['http_proxy']).to eq("#{scheme}://username:%3AP%40ssword101@#{address}:#{port}") + expect(@env['HTTP_PROXY']).to eq("#{scheme}://username:%3AP%40ssword101@#{address}:#{port}") end end end @@ -319,8 +319,8 @@ describe Chef::Application do it "should set ENV['http_proxy']" do @app.configure_proxy_environment_variables - @env['http_proxy'].should == "#{scheme}://#{address}:#{port}" - @env['HTTP_PROXY'].should == "#{scheme}://#{address}:#{port}" + expect(@env['http_proxy']).to eq("#{scheme}://#{address}:#{port}") + expect(@env['HTTP_PROXY']).to eq("#{scheme}://#{address}:#{port}") end end end @@ -328,11 +328,11 @@ describe Chef::Application do describe "when configuring ENV['http_proxy']" do before do @env = {} - @app.stub(:env).and_return(@env) + allow(@app).to receive(:env).and_return(@env) - @app.stub(:configure_https_proxy).and_return(true) - @app.stub(:configure_ftp_proxy).and_return(true) - @app.stub(:configure_no_proxy).and_return(true) + allow(@app).to receive(:configure_https_proxy).and_return(true) + allow(@app).to receive(:configure_ftp_proxy).and_return(true) + allow(@app).to receive(:configure_no_proxy).and_return(true) end describe "when Chef::Config[:http_proxy] is not set" do @@ -342,7 +342,7 @@ describe Chef::Application do it "should not set ENV['http_proxy']" do @app.configure_proxy_environment_variables - @env.should == {} + expect(@env).to eq({}) end end @@ -401,7 +401,7 @@ describe Chef::Application do it "should set ENV['http_proxy']" do @app.configure_proxy_environment_variables - @env['http_proxy'].should == Chef::Config[:http_proxy] + expect(@env['http_proxy']).to eq(Chef::Config[:http_proxy]) end end @@ -417,26 +417,26 @@ describe Chef::Application do describe "class method: fatal!" do before do - STDERR.stub(:puts).with("FATAL: blah").and_return(true) - Chef::Log.stub(:fatal).and_return(true) - Process.stub(:exit).and_return(true) + allow(STDERR).to receive(:puts).with("FATAL: blah").and_return(true) + allow(Chef::Log).to receive(:fatal).and_return(true) + allow(Process).to receive(:exit).and_return(true) end it "should log an error message to the logger" do - Chef::Log.should_receive(:fatal).with("blah").and_return(true) + expect(Chef::Log).to receive(:fatal).with("blah").and_return(true) Chef::Application.fatal! "blah" end describe "when an exit code is supplied" do it "should exit with the given exit code" do - Process.should_receive(:exit).with(-100).and_return(true) + expect(Process).to receive(:exit).with(-100).and_return(true) Chef::Application.fatal! "blah", -100 end end describe "when an exit code is not supplied" do it "should exit with the default exit code" do - Process.should_receive(:exit).with(-1).and_return(true) + expect(Process).to receive(:exit).with(-1).and_return(true) Chef::Application.fatal! "blah" end end @@ -449,7 +449,7 @@ describe Chef::Application do end it "should raise an error" do - lambda { @app.setup_application }.should raise_error(Chef::Exceptions::Application) + expect { @app.setup_application }.to raise_error(Chef::Exceptions::Application) end end @@ -459,7 +459,7 @@ describe Chef::Application do end it "should raise an error" do - lambda { @app.run_application }.should raise_error(Chef::Exceptions::Application) + expect { @app.run_application }.to raise_error(Chef::Exceptions::Application) end end @@ -467,22 +467,22 @@ describe Chef::Application do it "should warn for bad config file path" do @app.config[:config_file] = "/tmp/non-existing-dir/file" config_file_regexp = Regexp.new @app.config[:config_file] - Chef::Log.should_receive(:warn).at_least(:once).with(config_file_regexp).and_return(true) - Chef::Log.stub(:warn).and_return(true) + expect(Chef::Log).to receive(:warn).at_least(:once).with(config_file_regexp).and_return(true) + allow(Chef::Log).to receive(:warn).and_return(true) @app.configure_chef end end describe "configuration errors" do before do - Process.should_receive(:exit) + expect(Process).to receive(:exit) end def raises_informative_fatals_on_configure_chef config_file_regexp = Regexp.new @app.config[:config_file] - Chef::Log.should_receive(:fatal). + expect(Chef::Log).to receive(:fatal). with(/Configuration error/) - Chef::Log.should_receive(:fatal). + expect(Chef::Log).to receive(:fatal). with(config_file_regexp). at_least(1).times @app.configure_chef diff --git a/spec/unit/chef_fs/diff_spec.rb b/spec/unit/chef_fs/diff_spec.rb index 2133d05139..71605393f3 100644 --- a/spec/unit/chef_fs/diff_spec.rb +++ b/spec/unit/chef_fs/diff_spec.rb @@ -91,7 +91,7 @@ describe 'diff', :uses_diff => true do Chef::ChefFS::CommandLine.diff_print(pattern('/'), a, b, nil, nil) do |diff| results << remove_os_differences(diff) end - results.should =~ [ + expect(results).to match_array([ 'diff --knife a/both_dirs/sub_both_files_different b/both_dirs/sub_both_files_different --- a/both_dirs/sub_both_files_different DATE +++ b/both_dirs/sub_both_files_different DATE @@ -160,14 +160,14 @@ new file +++ b/b_only_file DATE CONTEXT_LINE_NUMBERS +b_only_file -' ] +' ]) end it 'Chef::ChefFS::CommandLine.diff_print(/both_dirs)' do results = [] Chef::ChefFS::CommandLine.diff_print(pattern('/both_dirs'), a, b, nil, nil) do |diff| results << remove_os_differences(diff) end - results.should =~ [ + expect(results).to match_array([ 'diff --knife a/both_dirs/sub_both_files_different b/both_dirs/sub_both_files_different --- a/both_dirs/sub_both_files_different DATE +++ b/both_dirs/sub_both_files_different DATE @@ -202,14 +202,14 @@ new file +++ b/both_dirs/sub_b_only_file DATE CONTEXT_LINE_NUMBERS +sub_b_only_file -' ] +' ]) end it 'Chef::ChefFS::CommandLine.diff_print(/) with depth 1' do results = [] Chef::ChefFS::CommandLine.diff_print(pattern('/'), a, b, 1, nil) do |diff| results << remove_os_differences(diff) end - results.should =~ [ + expect(results).to match_array([ 'Common subdirectories: b/both_dirs ','diff --knife a/both_files_different b/both_files_different --- a/both_files_different DATE @@ -236,14 +236,14 @@ new file +++ b/b_only_file DATE CONTEXT_LINE_NUMBERS +b_only_file -' ] +' ]) end it 'Chef::ChefFS::CommandLine.diff_print(/*_*) with depth 0' do results = [] Chef::ChefFS::CommandLine.diff_print(pattern('/*_*'), a, b, 0, nil) do |diff| results << remove_os_differences(diff) end - results.should =~ [ + expect(results).to match_array([ 'Common subdirectories: b/both_dirs ','diff --knife a/both_files_different b/both_files_different --- a/both_files_different DATE @@ -270,14 +270,14 @@ new file +++ b/b_only_file DATE CONTEXT_LINE_NUMBERS +b_only_file -' ] +' ]) end it 'Chef::ChefFS::CommandLine.diff_print(/) in name-only mode' do results = [] Chef::ChefFS::CommandLine.diff_print(pattern('/'), a, b, nil, :name_only) do |diff| results << remove_os_differences(diff) end - results.should =~ [ + expect(results).to match_array([ "b/both_dirs/sub_both_files_different\n", "b/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub\n", "b/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub\n", @@ -296,14 +296,14 @@ CONTEXT_LINE_NUMBERS "b/b_only_file\n", "b/dir_in_a_file_in_b\n", "b/file_in_a_dir_in_b\n" - ] + ]) end it 'Chef::ChefFS::CommandLine.diff_print(/) in name-status mode' do results = [] Chef::ChefFS::CommandLine.diff_print(pattern('/'), a, b, nil, :name_status) do |diff| results << remove_os_differences(diff) end - results.should =~ [ + expect(results).to match_array([ "M\tb/both_dirs/sub_both_files_different\n", "D\tb/both_dirs/sub_dirs_empty_in_b_filled_in_a/subsub\n", "A\tb/both_dirs/sub_dirs_empty_in_a_filled_in_b/subsub\n", @@ -322,7 +322,7 @@ CONTEXT_LINE_NUMBERS "A\tb/b_only_file\n", "T\tb/dir_in_a_file_in_b\n", "T\tb/file_in_a_dir_in_b\n" - ] + ]) end end end diff --git a/spec/unit/chef_fs/file_pattern_spec.rb b/spec/unit/chef_fs/file_pattern_spec.rb index bac393a054..cdf506225a 100644 --- a/spec/unit/chef_fs/file_pattern_spec.rb +++ b/spec/unit/chef_fs/file_pattern_spec.rb @@ -28,466 +28,465 @@ describe Chef::ChefFS::FilePattern do context 'with empty pattern ""' do let(:pattern) { Chef::ChefFS::FilePattern.new('') } it 'match?' do - pattern.match?('').should be_true - pattern.match?('/').should be_false - pattern.match?('a').should be_false - pattern.match?('a/b').should be_false + expect(pattern.match?('')).to be_truthy + expect(pattern.match?('/')).to be_falsey + expect(pattern.match?('a')).to be_falsey + expect(pattern.match?('a/b')).to be_falsey end it 'exact_path' do - pattern.exact_path.should == '' + expect(pattern.exact_path).to eq('') end it 'could_match_children?' do - pattern.could_match_children?('').should be_false - pattern.could_match_children?('a/b').should be_false + expect(pattern.could_match_children?('')).to be_falsey + expect(pattern.could_match_children?('a/b')).to be_falsey end end context 'with root pattern "/"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/') } it 'match?' do - pattern.match?('/').should be_true - pattern.match?('').should be_false - pattern.match?('a').should be_false - pattern.match?('/a').should be_false + expect(pattern.match?('/')).to be_truthy + expect(pattern.match?('')).to be_falsey + expect(pattern.match?('a')).to be_falsey + expect(pattern.match?('/a')).to be_falsey end it 'exact_path' do - pattern.exact_path.should == '/' + expect(pattern.exact_path).to eq('/') end it 'could_match_children?' do - pattern.could_match_children?('').should be_false - pattern.could_match_children?('/').should be_false - pattern.could_match_children?('a').should be_false - pattern.could_match_children?('a/b').should be_false - pattern.could_match_children?('/a').should be_false + expect(pattern.could_match_children?('')).to be_falsey + expect(pattern.could_match_children?('/')).to be_falsey + expect(pattern.could_match_children?('a')).to be_falsey + expect(pattern.could_match_children?('a/b')).to be_falsey + expect(pattern.could_match_children?('/a')).to be_falsey end end context 'with simple pattern "abc"' do let(:pattern) { Chef::ChefFS::FilePattern.new('abc') } it 'match?' do - pattern.match?('abc').should be_true - pattern.match?('a').should be_false - pattern.match?('abcd').should be_false - pattern.match?('/abc').should be_false - pattern.match?('').should be_false - pattern.match?('/').should be_false + expect(pattern.match?('abc')).to be_truthy + expect(pattern.match?('a')).to be_falsey + expect(pattern.match?('abcd')).to be_falsey + expect(pattern.match?('/abc')).to be_falsey + expect(pattern.match?('')).to be_falsey + expect(pattern.match?('/')).to be_falsey end it 'exact_path' do - pattern.exact_path.should == 'abc' + expect(pattern.exact_path).to eq('abc') end it 'could_match_children?' do - pattern.could_match_children?('').should be_false - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/abc').should be_false + expect(pattern.could_match_children?('')).to be_falsey + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/abc')).to be_falsey end end context 'with simple pattern "/abc"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc') } it 'match?' do - pattern.match?('/abc').should be_true - pattern.match?('abc').should be_false - pattern.match?('a').should be_false - pattern.match?('abcd').should be_false - pattern.match?('').should be_false - pattern.match?('/').should be_false + expect(pattern.match?('/abc')).to be_truthy + expect(pattern.match?('abc')).to be_falsey + expect(pattern.match?('a')).to be_falsey + expect(pattern.match?('abcd')).to be_falsey + expect(pattern.match?('')).to be_falsey + expect(pattern.match?('/')).to be_falsey end it 'exact_path' do - pattern.exact_path.should == '/abc' + expect(pattern.exact_path).to eq('/abc') end it 'could_match_children?' do - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/abc').should be_false - pattern.could_match_children?('/').should be_true - pattern.could_match_children?('').should be_false + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/abc')).to be_falsey + expect(pattern.could_match_children?('/')).to be_truthy + expect(pattern.could_match_children?('')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' + expect(pattern.exact_child_name_under('/')).to eq('abc') end end context 'with simple pattern "abc/def/ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('abc/def/ghi') } it 'match?' do - pattern.match?('abc/def/ghi').should be_true - pattern.match?('/abc/def/ghi').should be_false - pattern.match?('abc').should be_false - pattern.match?('abc/def').should be_false + expect(pattern.match?('abc/def/ghi')).to be_truthy + expect(pattern.match?('/abc/def/ghi')).to be_falsey + expect(pattern.match?('abc')).to be_falsey + expect(pattern.match?('abc/def')).to be_falsey end it 'exact_path' do - pattern.exact_path.should == 'abc/def/ghi' + expect(pattern.exact_path).to eq('abc/def/ghi') end it 'could_match_children?' do - pattern.could_match_children?('abc').should be_true - pattern.could_match_children?('xyz').should be_false - pattern.could_match_children?('/abc').should be_false - pattern.could_match_children?('abc/def').should be_true - pattern.could_match_children?('abc/xyz').should be_false - pattern.could_match_children?('abc/def/ghi').should be_false + expect(pattern.could_match_children?('abc')).to be_truthy + expect(pattern.could_match_children?('xyz')).to be_falsey + expect(pattern.could_match_children?('/abc')).to be_falsey + expect(pattern.could_match_children?('abc/def')).to be_truthy + expect(pattern.could_match_children?('abc/xyz')).to be_falsey + expect(pattern.could_match_children?('abc/def/ghi')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('abc').should == 'def' - pattern.exact_child_name_under('abc/def').should == 'ghi' + expect(pattern.exact_child_name_under('abc')).to eq('def') + expect(pattern.exact_child_name_under('abc/def')).to eq('ghi') end end context 'with simple pattern "/abc/def/ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc/def/ghi') } it 'match?' do - pattern.match?('/abc/def/ghi').should be_true - pattern.match?('abc/def/ghi').should be_false - pattern.match?('/abc').should be_false - pattern.match?('/abc/def').should be_false + expect(pattern.match?('/abc/def/ghi')).to be_truthy + expect(pattern.match?('abc/def/ghi')).to be_falsey + expect(pattern.match?('/abc')).to be_falsey + expect(pattern.match?('/abc/def')).to be_falsey end it 'exact_path' do - pattern.exact_path.should == '/abc/def/ghi' + expect(pattern.exact_path).to eq('/abc/def/ghi') end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/xyz').should be_false - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/abc/def').should be_true - pattern.could_match_children?('/abc/xyz').should be_false - pattern.could_match_children?('/abc/def/ghi').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/xyz')).to be_falsey + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/abc/def')).to be_truthy + expect(pattern.could_match_children?('/abc/xyz')).to be_falsey + expect(pattern.could_match_children?('/abc/def/ghi')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' - pattern.exact_child_name_under('/abc').should == 'def' - pattern.exact_child_name_under('/abc/def').should == 'ghi' + expect(pattern.exact_child_name_under('/')).to eq('abc') + expect(pattern.exact_child_name_under('/abc')).to eq('def') + expect(pattern.exact_child_name_under('/abc/def')).to eq('ghi') end end context 'with simple pattern "a\*\b"', :pending => (Chef::Platform.windows?) do let(:pattern) { Chef::ChefFS::FilePattern.new('a\*\b') } it 'match?' do - pattern.match?('a*b').should be_true - pattern.match?('ab').should be_false - pattern.match?('acb').should be_false - pattern.match?('ab').should be_false + expect(pattern.match?('a*b')).to be_truthy + expect(pattern.match?('ab')).to be_falsey + expect(pattern.match?('acb')).to be_falsey + expect(pattern.match?('ab')).to be_falsey end it 'exact_path' do - pattern.exact_path.should == 'a*b' + expect(pattern.exact_path).to eq('a*b') end it 'could_match_children?' do - pattern.could_match_children?('a/*b').should be_false + expect(pattern.could_match_children?('a/*b')).to be_falsey end end context 'with star pattern "/abc/*/ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc/*/ghi') } it 'match?' do - pattern.match?('/abc/def/ghi').should be_true - pattern.match?('/abc/ghi').should be_false + expect(pattern.match?('/abc/def/ghi')).to be_truthy + expect(pattern.match?('/abc/ghi')).to be_falsey end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/xyz').should be_false - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/abc/def').should be_true - pattern.could_match_children?('/abc/xyz').should be_true - pattern.could_match_children?('/abc/def/ghi').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/xyz')).to be_falsey + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/abc/def')).to be_truthy + expect(pattern.could_match_children?('/abc/xyz')).to be_truthy + expect(pattern.could_match_children?('/abc/def/ghi')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' - pattern.exact_child_name_under('/abc').should == nil - pattern.exact_child_name_under('/abc/def').should == 'ghi' + expect(pattern.exact_child_name_under('/')).to eq('abc') + expect(pattern.exact_child_name_under('/abc')).to eq(nil) + expect(pattern.exact_child_name_under('/abc/def')).to eq('ghi') end end context 'with star pattern "/abc/d*f/ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc/d*f/ghi') } it 'match?' do - pattern.match?('/abc/def/ghi').should be_true - pattern.match?('/abc/dxf/ghi').should be_true - pattern.match?('/abc/df/ghi').should be_true - pattern.match?('/abc/dxyzf/ghi').should be_true - pattern.match?('/abc/d/ghi').should be_false - pattern.match?('/abc/f/ghi').should be_false - pattern.match?('/abc/ghi').should be_false - pattern.match?('/abc/xyz/ghi').should be_false + expect(pattern.match?('/abc/def/ghi')).to be_truthy + expect(pattern.match?('/abc/dxf/ghi')).to be_truthy + expect(pattern.match?('/abc/df/ghi')).to be_truthy + expect(pattern.match?('/abc/dxyzf/ghi')).to be_truthy + expect(pattern.match?('/abc/d/ghi')).to be_falsey + expect(pattern.match?('/abc/f/ghi')).to be_falsey + expect(pattern.match?('/abc/ghi')).to be_falsey + expect(pattern.match?('/abc/xyz/ghi')).to be_falsey end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/xyz').should be_false - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/abc/def').should be_true - pattern.could_match_children?('/abc/xyz').should be_false - pattern.could_match_children?('/abc/dxyzf').should be_true - pattern.could_match_children?('/abc/df').should be_true - pattern.could_match_children?('/abc/d').should be_false - pattern.could_match_children?('/abc/f').should be_false - pattern.could_match_children?('/abc/def/ghi').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/xyz')).to be_falsey + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/abc/def')).to be_truthy + expect(pattern.could_match_children?('/abc/xyz')).to be_falsey + expect(pattern.could_match_children?('/abc/dxyzf')).to be_truthy + expect(pattern.could_match_children?('/abc/df')).to be_truthy + expect(pattern.could_match_children?('/abc/d')).to be_falsey + expect(pattern.could_match_children?('/abc/f')).to be_falsey + expect(pattern.could_match_children?('/abc/def/ghi')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' - pattern.exact_child_name_under('/abc').should == nil - pattern.exact_child_name_under('/abc/def').should == 'ghi' + expect(pattern.exact_child_name_under('/')).to eq('abc') + expect(pattern.exact_child_name_under('/abc')).to eq(nil) + expect(pattern.exact_child_name_under('/abc/def')).to eq('ghi') end end context 'with star pattern "/abc/d??f/ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc/d??f/ghi') } it 'match?' do - pattern.match?('/abc/deef/ghi').should be_true - pattern.match?('/abc/deeef/ghi').should be_false - pattern.match?('/abc/def/ghi').should be_false - pattern.match?('/abc/df/ghi').should be_false - pattern.match?('/abc/d/ghi').should be_false - pattern.match?('/abc/f/ghi').should be_false - pattern.match?('/abc/ghi').should be_false + expect(pattern.match?('/abc/deef/ghi')).to be_truthy + expect(pattern.match?('/abc/deeef/ghi')).to be_falsey + expect(pattern.match?('/abc/def/ghi')).to be_falsey + expect(pattern.match?('/abc/df/ghi')).to be_falsey + expect(pattern.match?('/abc/d/ghi')).to be_falsey + expect(pattern.match?('/abc/f/ghi')).to be_falsey + expect(pattern.match?('/abc/ghi')).to be_falsey end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/xyz').should be_false - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/abc/deef').should be_true - pattern.could_match_children?('/abc/deeef').should be_false - pattern.could_match_children?('/abc/def').should be_false - pattern.could_match_children?('/abc/df').should be_false - pattern.could_match_children?('/abc/d').should be_false - pattern.could_match_children?('/abc/f').should be_false - pattern.could_match_children?('/abc/deef/ghi').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/xyz')).to be_falsey + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/abc/deef')).to be_truthy + expect(pattern.could_match_children?('/abc/deeef')).to be_falsey + expect(pattern.could_match_children?('/abc/def')).to be_falsey + expect(pattern.could_match_children?('/abc/df')).to be_falsey + expect(pattern.could_match_children?('/abc/d')).to be_falsey + expect(pattern.could_match_children?('/abc/f')).to be_falsey + expect(pattern.could_match_children?('/abc/deef/ghi')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' - pattern.exact_child_name_under('/abc').should == nil - pattern.exact_child_name_under('/abc/deef').should == 'ghi' + expect(pattern.exact_child_name_under('/')).to eq('abc') + expect(pattern.exact_child_name_under('/abc')).to eq(nil) + expect(pattern.exact_child_name_under('/abc/deef')).to eq('ghi') end end context 'with star pattern "/abc/d[a-z][0-9]f/ghi"', :pending => (Chef::Platform.windows?) do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc/d[a-z][0-9]f/ghi') } it 'match?' do - pattern.match?('/abc/de1f/ghi').should be_true - pattern.match?('/abc/deef/ghi').should be_false - pattern.match?('/abc/d11f/ghi').should be_false - pattern.match?('/abc/de11f/ghi').should be_false - pattern.match?('/abc/dee1f/ghi').should be_false - pattern.match?('/abc/df/ghi').should be_false - pattern.match?('/abc/d/ghi').should be_false - pattern.match?('/abc/f/ghi').should be_false - pattern.match?('/abc/ghi').should be_false + expect(pattern.match?('/abc/de1f/ghi')).to be_truthy + expect(pattern.match?('/abc/deef/ghi')).to be_falsey + expect(pattern.match?('/abc/d11f/ghi')).to be_falsey + expect(pattern.match?('/abc/de11f/ghi')).to be_falsey + expect(pattern.match?('/abc/dee1f/ghi')).to be_falsey + expect(pattern.match?('/abc/df/ghi')).to be_falsey + expect(pattern.match?('/abc/d/ghi')).to be_falsey + expect(pattern.match?('/abc/f/ghi')).to be_falsey + expect(pattern.match?('/abc/ghi')).to be_falsey end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/xyz').should be_false - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/abc/de1f').should be_true - pattern.could_match_children?('/abc/deef').should be_false - pattern.could_match_children?('/abc/d11f').should be_false - pattern.could_match_children?('/abc/de11f').should be_false - pattern.could_match_children?('/abc/dee1f').should be_false - pattern.could_match_children?('/abc/def').should be_false - pattern.could_match_children?('/abc/df').should be_false - pattern.could_match_children?('/abc/d').should be_false - pattern.could_match_children?('/abc/f').should be_false - pattern.could_match_children?('/abc/de1f/ghi').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/xyz')).to be_falsey + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/abc/de1f')).to be_truthy + expect(pattern.could_match_children?('/abc/deef')).to be_falsey + expect(pattern.could_match_children?('/abc/d11f')).to be_falsey + expect(pattern.could_match_children?('/abc/de11f')).to be_falsey + expect(pattern.could_match_children?('/abc/dee1f')).to be_falsey + expect(pattern.could_match_children?('/abc/def')).to be_falsey + expect(pattern.could_match_children?('/abc/df')).to be_falsey + expect(pattern.could_match_children?('/abc/d')).to be_falsey + expect(pattern.could_match_children?('/abc/f')).to be_falsey + expect(pattern.could_match_children?('/abc/de1f/ghi')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' - pattern.exact_child_name_under('/abc').should == nil - pattern.exact_child_name_under('/abc/de1f').should == 'ghi' + expect(pattern.exact_child_name_under('/')).to eq('abc') + expect(pattern.exact_child_name_under('/abc')).to eq(nil) + expect(pattern.exact_child_name_under('/abc/de1f')).to eq('ghi') end end context 'with star pattern "/abc/**/ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc/**/ghi') } it 'match?' do - pattern.match?('/abc/def/ghi').should be_true - pattern.match?('/abc/d/e/f/ghi').should be_true - pattern.match?('/abc/ghi').should be_false - pattern.match?('/abcdef/d/ghi').should be_false - pattern.match?('/abc/d/defghi').should be_false - pattern.match?('/xyz').should be_false + expect(pattern.match?('/abc/def/ghi')).to be_truthy + expect(pattern.match?('/abc/d/e/f/ghi')).to be_truthy + expect(pattern.match?('/abc/ghi')).to be_falsey + expect(pattern.match?('/abcdef/d/ghi')).to be_falsey + expect(pattern.match?('/abc/d/defghi')).to be_falsey + expect(pattern.match?('/xyz')).to be_falsey end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/abc/d').should be_true - pattern.could_match_children?('/abc/d/e').should be_true - pattern.could_match_children?('/abc/d/e/f').should be_true - pattern.could_match_children?('/abc/def/ghi').should be_true - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/xyz').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/abc/d')).to be_truthy + expect(pattern.could_match_children?('/abc/d/e')).to be_truthy + expect(pattern.could_match_children?('/abc/d/e/f')).to be_truthy + expect(pattern.could_match_children?('/abc/def/ghi')).to be_truthy + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/xyz')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' - pattern.exact_child_name_under('/abc').should == nil - pattern.exact_child_name_under('/abc/def').should == nil + expect(pattern.exact_child_name_under('/')).to eq('abc') + expect(pattern.exact_child_name_under('/abc')).to eq(nil) + expect(pattern.exact_child_name_under('/abc/def')).to eq(nil) end end context 'with star pattern "/abc**/ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc**/ghi') } it 'match?' do - pattern.match?('/abc/def/ghi').should be_true - pattern.match?('/abc/d/e/f/ghi').should be_true - pattern.match?('/abc/ghi').should be_true - pattern.match?('/abcdef/ghi').should be_true - pattern.match?('/abc/defghi').should be_false - pattern.match?('/xyz').should be_false + expect(pattern.match?('/abc/def/ghi')).to be_truthy + expect(pattern.match?('/abc/d/e/f/ghi')).to be_truthy + expect(pattern.match?('/abc/ghi')).to be_truthy + expect(pattern.match?('/abcdef/ghi')).to be_truthy + expect(pattern.match?('/abc/defghi')).to be_falsey + expect(pattern.match?('/xyz')).to be_falsey end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/abcdef').should be_true - pattern.could_match_children?('/abc/d/e').should be_true - pattern.could_match_children?('/abc/d/e/f').should be_true - pattern.could_match_children?('/abc/def/ghi').should be_true - pattern.could_match_children?('abc').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/abcdef')).to be_truthy + expect(pattern.could_match_children?('/abc/d/e')).to be_truthy + expect(pattern.could_match_children?('/abc/d/e/f')).to be_truthy + expect(pattern.could_match_children?('/abc/def/ghi')).to be_truthy + expect(pattern.could_match_children?('abc')).to be_falsey end it 'could_match_children? /abc** returns false for /xyz' do - pending 'Make could_match_children? more rigorous' do - # At the moment, we return false for this, but in the end it would be nice to return true: - pattern.could_match_children?('/xyz').should be_false - end + pending 'Make could_match_children? more rigorous' + # At the moment, we return false for this, but in the end it would be nice to return true: + pattern.could_match_children?('/xyz').should be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == nil - pattern.exact_child_name_under('/abc').should == nil - pattern.exact_child_name_under('/abc/def').should == nil + expect(pattern.exact_child_name_under('/')).to eq(nil) + expect(pattern.exact_child_name_under('/abc')).to eq(nil) + expect(pattern.exact_child_name_under('/abc/def')).to eq(nil) end end context 'with star pattern "/abc/**ghi"' do let(:pattern) { Chef::ChefFS::FilePattern.new('/abc/**ghi') } it 'match?' do - pattern.match?('/abc/def/ghi').should be_true - pattern.match?('/abc/def/ghi/ghi').should be_true - pattern.match?('/abc/def/ghi/jkl').should be_false - pattern.match?('/abc/d/e/f/ghi').should be_true - pattern.match?('/abc/ghi').should be_true - pattern.match?('/abcdef/ghi').should be_false - pattern.match?('/abc/defghi').should be_true - pattern.match?('/xyz').should be_false + expect(pattern.match?('/abc/def/ghi')).to be_truthy + expect(pattern.match?('/abc/def/ghi/ghi')).to be_truthy + expect(pattern.match?('/abc/def/ghi/jkl')).to be_falsey + expect(pattern.match?('/abc/d/e/f/ghi')).to be_truthy + expect(pattern.match?('/abc/ghi')).to be_truthy + expect(pattern.match?('/abcdef/ghi')).to be_falsey + expect(pattern.match?('/abc/defghi')).to be_truthy + expect(pattern.match?('/xyz')).to be_falsey end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end it 'could_match_children?' do - pattern.could_match_children?('/abc').should be_true - pattern.could_match_children?('/abcdef').should be_false - pattern.could_match_children?('/abc/d/e').should be_true - pattern.could_match_children?('/abc/d/e/f').should be_true - pattern.could_match_children?('/abc/def/ghi').should be_true - pattern.could_match_children?('abc').should be_false - pattern.could_match_children?('/xyz').should be_false + expect(pattern.could_match_children?('/abc')).to be_truthy + expect(pattern.could_match_children?('/abcdef')).to be_falsey + expect(pattern.could_match_children?('/abc/d/e')).to be_truthy + expect(pattern.could_match_children?('/abc/d/e/f')).to be_truthy + expect(pattern.could_match_children?('/abc/def/ghi')).to be_truthy + expect(pattern.could_match_children?('abc')).to be_falsey + expect(pattern.could_match_children?('/xyz')).to be_falsey end it 'exact_child_name_under' do - pattern.exact_child_name_under('/').should == 'abc' - pattern.exact_child_name_under('/abc').should == nil - pattern.exact_child_name_under('/abc/def').should == nil + expect(pattern.exact_child_name_under('/')).to eq('abc') + expect(pattern.exact_child_name_under('/abc')).to eq(nil) + expect(pattern.exact_child_name_under('/abc/def')).to eq(nil) end end context 'with star pattern "a**b**c"' do let(:pattern) { Chef::ChefFS::FilePattern.new('a**b**c') } it 'match?' do - pattern.match?('axybzwc').should be_true - pattern.match?('abc').should be_true - pattern.match?('axyzwc').should be_false - pattern.match?('ac').should be_false - pattern.match?('a/x/y/b/z/w/c').should be_true + expect(pattern.match?('axybzwc')).to be_truthy + expect(pattern.match?('abc')).to be_truthy + expect(pattern.match?('axyzwc')).to be_falsey + expect(pattern.match?('ac')).to be_falsey + expect(pattern.match?('a/x/y/b/z/w/c')).to be_truthy end it 'exact_path' do - pattern.exact_path.should be_nil + expect(pattern.exact_path).to be_nil end end context 'normalization tests' do it 'handles trailing slashes' do - p('abc/').normalized_pattern.should == 'abc' - p('abc/').exact_path.should == 'abc' - p('abc/').match?('abc').should be_true - p('//').normalized_pattern.should == '/' - p('//').exact_path.should == '/' - p('//').match?('/').should be_true - p('/./').normalized_pattern.should == '/' - p('/./').exact_path.should == '/' - p('/./').match?('/').should be_true + expect(p('abc/').normalized_pattern).to eq('abc') + expect(p('abc/').exact_path).to eq('abc') + expect(p('abc/').match?('abc')).to be_truthy + expect(p('//').normalized_pattern).to eq('/') + expect(p('//').exact_path).to eq('/') + expect(p('//').match?('/')).to be_truthy + expect(p('/./').normalized_pattern).to eq('/') + expect(p('/./').exact_path).to eq('/') + expect(p('/./').match?('/')).to be_truthy end it 'handles multiple slashes' do - p('abc//def').normalized_pattern.should == 'abc/def' - p('abc//def').exact_path.should == 'abc/def' - p('abc//def').match?('abc/def').should be_true - p('abc//').normalized_pattern.should == 'abc' - p('abc//').exact_path.should == 'abc' - p('abc//').match?('abc').should be_true + expect(p('abc//def').normalized_pattern).to eq('abc/def') + expect(p('abc//def').exact_path).to eq('abc/def') + expect(p('abc//def').match?('abc/def')).to be_truthy + expect(p('abc//').normalized_pattern).to eq('abc') + expect(p('abc//').exact_path).to eq('abc') + expect(p('abc//').match?('abc')).to be_truthy end it 'handles dot' do - p('abc/./def').normalized_pattern.should == 'abc/def' - p('abc/./def').exact_path.should == 'abc/def' - p('abc/./def').match?('abc/def').should be_true - p('./abc/def').normalized_pattern.should == 'abc/def' - p('./abc/def').exact_path.should == 'abc/def' - p('./abc/def').match?('abc/def').should be_true - p('/.').normalized_pattern.should == '/' - p('/.').exact_path.should == '/' - p('/.').match?('/').should be_true + expect(p('abc/./def').normalized_pattern).to eq('abc/def') + expect(p('abc/./def').exact_path).to eq('abc/def') + expect(p('abc/./def').match?('abc/def')).to be_truthy + expect(p('./abc/def').normalized_pattern).to eq('abc/def') + expect(p('./abc/def').exact_path).to eq('abc/def') + expect(p('./abc/def').match?('abc/def')).to be_truthy + expect(p('/.').normalized_pattern).to eq('/') + expect(p('/.').exact_path).to eq('/') + expect(p('/.').match?('/')).to be_truthy end it 'handles dot by itself', :pending => "decide what to do with dot by itself" do - p('.').normalized_pattern.should == '.' - p('.').exact_path.should == '.' - p('.').match?('.').should be_true - p('./').normalized_pattern.should == '.' - p('./').exact_path.should == '.' - p('./').match?('.').should be_true + expect(p('.').normalized_pattern).to eq('.') + expect(p('.').exact_path).to eq('.') + expect(p('.').match?('.')).to be_truthy + expect(p('./').normalized_pattern).to eq('.') + expect(p('./').exact_path).to eq('.') + expect(p('./').match?('.')).to be_truthy end it 'handles dotdot' do - p('abc/../def').normalized_pattern.should == 'def' - p('abc/../def').exact_path.should == 'def' - p('abc/../def').match?('def').should be_true - p('abc/def/../..').normalized_pattern.should == '' - p('abc/def/../..').exact_path.should == '' - p('abc/def/../..').match?('').should be_true - p('/*/../def').normalized_pattern.should == '/def' - p('/*/../def').exact_path.should == '/def' - p('/*/../def').match?('/def').should be_true - p('/*/*/../def').normalized_pattern.should == '/*/def' - p('/*/*/../def').exact_path.should be_nil - p('/*/*/../def').match?('/abc/def').should be_true - p('/abc/def/../..').normalized_pattern.should == '/' - p('/abc/def/../..').exact_path.should == '/' - p('/abc/def/../..').match?('/').should be_true - p('abc/../../def').normalized_pattern.should == '../def' - p('abc/../../def').exact_path.should == '../def' - p('abc/../../def').match?('../def').should be_true + expect(p('abc/../def').normalized_pattern).to eq('def') + expect(p('abc/../def').exact_path).to eq('def') + expect(p('abc/../def').match?('def')).to be_truthy + expect(p('abc/def/../..').normalized_pattern).to eq('') + expect(p('abc/def/../..').exact_path).to eq('') + expect(p('abc/def/../..').match?('')).to be_truthy + expect(p('/*/../def').normalized_pattern).to eq('/def') + expect(p('/*/../def').exact_path).to eq('/def') + expect(p('/*/../def').match?('/def')).to be_truthy + expect(p('/*/*/../def').normalized_pattern).to eq('/*/def') + expect(p('/*/*/../def').exact_path).to be_nil + expect(p('/*/*/../def').match?('/abc/def')).to be_truthy + expect(p('/abc/def/../..').normalized_pattern).to eq('/') + expect(p('/abc/def/../..').exact_path).to eq('/') + expect(p('/abc/def/../..').match?('/')).to be_truthy + expect(p('abc/../../def').normalized_pattern).to eq('../def') + expect(p('abc/../../def').exact_path).to eq('../def') + expect(p('abc/../../def').match?('../def')).to be_truthy end it 'handles dotdot with double star' do - p('abc**/def/../ghi').exact_path.should be_nil - p('abc**/def/../ghi').match?('abc/ghi').should be_true - p('abc**/def/../ghi').match?('abc/x/y/z/ghi').should be_true - p('abc**/def/../ghi').match?('ghi').should be_false + expect(p('abc**/def/../ghi').exact_path).to be_nil + expect(p('abc**/def/../ghi').match?('abc/ghi')).to be_truthy + expect(p('abc**/def/../ghi').match?('abc/x/y/z/ghi')).to be_truthy + expect(p('abc**/def/../ghi').match?('ghi')).to be_falsey end it 'raises error on dotdot with overlapping double star' do - lambda { Chef::ChefFS::FilePattern.new('abc/**/../def').exact_path }.should raise_error(ArgumentError) - lambda { Chef::ChefFS::FilePattern.new('abc/**/abc/../../def').exact_path }.should raise_error(ArgumentError) + expect { Chef::ChefFS::FilePattern.new('abc/**/../def').exact_path }.to raise_error(ArgumentError) + expect { Chef::ChefFS::FilePattern.new('abc/**/abc/../../def').exact_path }.to raise_error(ArgumentError) end it 'handles leading dotdot' do - p('../abc/def').exact_path.should == '../abc/def' - p('../abc/def').match?('../abc/def').should be_true - p('/../abc/def').exact_path.should == '/abc/def' - p('/../abc/def').match?('/abc/def').should be_true - p('..').exact_path.should == '..' - p('..').match?('..').should be_true - p('/..').exact_path.should == '/' - p('/..').match?('/').should be_true + expect(p('../abc/def').exact_path).to eq('../abc/def') + expect(p('../abc/def').match?('../abc/def')).to be_truthy + expect(p('/../abc/def').exact_path).to eq('/abc/def') + expect(p('/../abc/def').match?('/abc/def')).to be_truthy + expect(p('..').exact_path).to eq('..') + expect(p('..').match?('..')).to be_truthy + expect(p('/..').exact_path).to eq('/') + expect(p('/..').match?('/')).to be_truthy end end diff --git a/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb b/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb index 570246c41f..142755a4f1 100644 --- a/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb +++ b/spec/unit/chef_fs/file_system/operation_failed_error_spec.rb @@ -27,20 +27,20 @@ describe Chef::ChefFS::FileSystem::OperationFailedError do it 'include error cause' do allow_message_expectations_on_nil response_body = '{"error":["Invalid key test in request body"]}' - @response.stub(:code).and_return("400") - @response.stub(:body).and_return(response_body) + allow(@response).to receive(:code).and_return("400") + allow(@response).to receive(:body).and_return(response_body) exception = Net::HTTPServerException.new("(exception) unauthorized", @response) - proc { + expect { raise Chef::ChefFS::FileSystem::OperationFailedError.new(:write, self, exception), error_message - }.should raise_error(Chef::ChefFS::FileSystem::OperationFailedError, "#{error_message} cause: #{response_body}") + }.to raise_error(Chef::ChefFS::FileSystem::OperationFailedError, "#{error_message} cause: #{response_body}") end end context 'does not have a cause attribute' do it 'does not include error cause' do - proc { + expect { raise Chef::ChefFS::FileSystem::OperationFailedError.new(:write, self), error_message - }.should raise_error(Chef::ChefFS::FileSystem::OperationFailedError, error_message) + }.to raise_error(Chef::ChefFS::FileSystem::OperationFailedError, error_message) end end end diff --git a/spec/unit/chef_fs/file_system_spec.rb b/spec/unit/chef_fs/file_system_spec.rb index 50f20a7a1c..75ca4d4be9 100644 --- a/spec/unit/chef_fs/file_system_spec.rb +++ b/spec/unit/chef_fs/file_system_spec.rb @@ -43,13 +43,13 @@ describe Chef::ChefFS::FileSystem do context 'resolve_path' do it '/' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/').path.should == '/' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/').path).to eq('/') end it 'nonexistent /a' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/a').path.should == '/a' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/a').path).to eq('/a') end it 'nonexistent /a/b' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/a/b').path.should == '/a/b' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/a/b').path).to eq('/a/b') end end end @@ -114,34 +114,34 @@ describe Chef::ChefFS::FileSystem do no_blocking_calls_allowed end it 'resolves /' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/').path.should == '/' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/').path).to eq('/') end it 'resolves /x' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/x').path.should == '/x' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/x').path).to eq('/x') end it 'resolves /a' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/a').path.should == '/a' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/a').path).to eq('/a') end it 'resolves /a/aa' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/a/aa').path.should == '/a/aa' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/a/aa').path).to eq('/a/aa') end it 'resolves /a/aa/zz' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/a/aa/zz').path.should == '/a/aa/zz' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/a/aa/zz').path).to eq('/a/aa/zz') end it 'resolves nonexistent /q/x/w' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/q/x/w').path.should == '/q/x/w' + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/q/x/w').path).to eq('/q/x/w') end end context 'empty?' do it 'is not empty /' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/').empty?.should be false + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/').empty?).to be false end it 'is empty /y' do - Chef::ChefFS::FileSystem.resolve_path(fs, '/y').empty?.should be true + expect(Chef::ChefFS::FileSystem.resolve_path(fs, '/y').empty?).to be true end it 'is not a directory and can\'t be tested /x' do - lambda { Chef::ChefFS::FileSystem.resolve_path(fs, '/x').empty? }.should raise_error(NoMethodError) + expect { Chef::ChefFS::FileSystem.resolve_path(fs, '/x').empty? }.to raise_error(NoMethodError) end end end diff --git a/spec/unit/chef_fs/parallelizer.rb b/spec/unit/chef_fs/parallelizer.rb index a871b60e98..9cb97963ed 100644 --- a/spec/unit/chef_fs/parallelizer.rb +++ b/spec/unit/chef_fs/parallelizer.rb @@ -29,8 +29,8 @@ describe Chef::ChefFS::Parallelizer do sleep val outputs << val end - elapsed_time.should < 0.6 - outputs.should == [ 0.1, 0.3, 0.5 ] + expect(elapsed_time).to be < 0.6 + expect(outputs).to eq([ 0.1, 0.3, 0.5 ]) end context "With :ordered => false (unordered output)" do @@ -38,15 +38,15 @@ describe Chef::ChefFS::Parallelizer do parallelize([], :ordered => false) do sleep 10 end.to_a == [] - elapsed_time.should < 0.1 + expect(elapsed_time).to be < 0.1 end it "10 sleep(0.2)s complete within 0.5 seconds" do - parallelize(1.upto(10), :ordered => false) do |i| + expect(parallelize(1.upto(10), :ordered => false) do |i| sleep 0.2 'x' - end.to_a.should == %w(x x x x x x x x x x) - elapsed_time.should < 0.5 + end.to_a).to eq(%w(x x x x x x x x x x)) + expect(elapsed_time).to be < 0.5 end it "The output comes as soon as it is available" do @@ -54,10 +54,10 @@ describe Chef::ChefFS::Parallelizer do sleep val val end - enum.map do |value| - elapsed_time.should < value+0.1 + expect(enum.map do |value| + expect(elapsed_time).to be < value+0.1 value - end.should == [ 0.1, 0.3, 0.5 ] + end).to eq([ 0.1, 0.3, 0.5 ]) end it "An exception in input is passed through but does NOT stop processing" do @@ -67,8 +67,8 @@ describe Chef::ChefFS::Parallelizer do enum = parallelize(input, :ordered => false) { |x| sleep(x); x } results = [] expect { enum.each { |value| results << value } }.to raise_error 'hi' - results.should == [ 0.1, 0.3, 0.5 ] - elapsed_time.should < 0.6 + expect(results).to eq([ 0.1, 0.3, 0.5 ]) + expect(elapsed_time).to be < 0.6 end it "Exceptions in output are raised after all processing is done" do @@ -84,9 +84,9 @@ describe Chef::ChefFS::Parallelizer do end results = [] expect { enum.each { |value| results << value } }.to raise_error 'hi' - results.sort.should == [ 1, 2, 3 ] - elapsed_time.should < 0.3 - processed.should == 3 + expect(results.sort).to eq([ 1, 2, 3 ]) + expect(elapsed_time).to be < 0.3 + expect(processed).to eq(3) end it "Exceptions with :stop_on_exception are raised after all processing is done" do @@ -101,7 +101,7 @@ describe Chef::ChefFS::Parallelizer do x end expect { parallelized.to_a }.to raise_error 'hi' - processed.should == 4 + expect(processed).to eq(4) end end @@ -110,15 +110,15 @@ describe Chef::ChefFS::Parallelizer do parallelize([]) do sleep 10 end.to_a == [] - elapsed_time.should < 0.1 + expect(elapsed_time).to be < 0.1 end it "10 sleep(0.2)s complete within 0.5 seconds" do - parallelize(1.upto(10), :ordered => true) do |i| + expect(parallelize(1.upto(10), :ordered => true) do |i| sleep 0.2 'x' - end.to_a.should == %w(x x x x x x x x x x) - elapsed_time.should < 0.5 + end.to_a).to eq(%w(x x x x x x x x x x)) + expect(elapsed_time).to be < 0.5 end it "Output comes in the order of the input" do @@ -126,10 +126,10 @@ describe Chef::ChefFS::Parallelizer do sleep val val end.enum_for(:each_with_index) - enum.next.should == [ 0.5, 0 ] - enum.next.should == [ 0.3, 1 ] - enum.next.should == [ 0.1, 2 ] - elapsed_time.should < 0.6 + expect(enum.next).to eq([ 0.5, 0 ]) + expect(enum.next).to eq([ 0.3, 1 ]) + expect(enum.next).to eq([ 0.1, 2 ]) + expect(elapsed_time).to be < 0.6 end it "Exceptions in input are raised in the correct sequence but do NOT stop processing" do @@ -139,8 +139,8 @@ describe Chef::ChefFS::Parallelizer do results = [] enum = parallelize(input) { |x| sleep(x); x } expect { enum.each { |value| results << value } }.to raise_error 'hi' - elapsed_time.should < 0.6 - results.should == [ 0.5, 0.3, 0.1 ] + expect(elapsed_time).to be < 0.6 + expect(results).to eq([ 0.5, 0.3, 0.1 ]) end it "Exceptions in output are raised in the correct sequence and running processes do NOT stop processing" do @@ -156,9 +156,9 @@ describe Chef::ChefFS::Parallelizer do end results = [] expect { enum.each { |value| results << value } }.to raise_error 'hi' - results.should == [ 1, 2 ] - elapsed_time.should < 0.3 - processed.should == 3 + expect(results).to eq([ 1, 2 ]) + expect(elapsed_time).to be < 0.3 + expect(processed).to eq(3) end it "Exceptions with :stop_on_exception are raised after all processing is done" do @@ -173,7 +173,7 @@ describe Chef::ChefFS::Parallelizer do x end expect { parallelized.to_a }.to raise_error 'hi' - processed.should == 4 + expect(processed).to eq(4) end end @@ -187,10 +187,10 @@ describe Chef::ChefFS::Parallelizer do sleep 0.1 end enum = parallelize(input) { |x| x } - enum.map do |value| - elapsed_time.should < (value+1)*0.1 + expect(enum.map do |value| + expect(elapsed_time).to be < (value+1)*0.1 value - end.should == [ 1, 2, 3 ] + end).to eq([ 1, 2, 3 ]) end end @@ -226,44 +226,44 @@ describe Chef::ChefFS::Parallelizer do end it "parallelize with :main_thread_processing = true does not block" do - parallelizer.parallelize([1]) do |x| + expect(parallelizer.parallelize([1]) do |x| sleep(0.1) x - end.to_a.should == [ 1 ] - elapsed_time.should < 0.2 + end.to_a).to eq([ 1 ]) + expect(elapsed_time).to be < 0.2 end it "parallelize with :main_thread_processing = false waits for the job to finish" do - parallelizer.parallelize([1], :main_thread_processing => false) do |x| + expect(parallelizer.parallelize([1], :main_thread_processing => false) do |x| sleep(0.1) x+1 - end.to_a.should == [ 2 ] - elapsed_time.should > 0.3 + end.to_a).to eq([ 2 ]) + expect(elapsed_time).to be > 0.3 end it "resizing the Parallelizer to 0 waits for the job to stop" do - elapsed_time.should < 0.2 + expect(elapsed_time).to be < 0.2 parallelizer.resize(0) - parallelizer.num_threads.should == 0 - elapsed_time.should > 0.25 - @occupying_job_finished.should == [ true ] + expect(parallelizer.num_threads).to eq(0) + expect(elapsed_time).to be > 0.25 + expect(@occupying_job_finished).to eq([ true ]) end it "stopping the Parallelizer waits for the job to finish" do - elapsed_time.should < 0.2 + expect(elapsed_time).to be < 0.2 parallelizer.stop - parallelizer.num_threads.should == 0 - elapsed_time.should > 0.25 - @occupying_job_finished.should == [ true ] + expect(parallelizer.num_threads).to eq(0) + expect(elapsed_time).to be > 0.25 + expect(@occupying_job_finished).to eq([ true ]) end it "resizing the Parallelizer to 2 does not stop the job" do - elapsed_time.should < 0.2 + expect(elapsed_time).to be < 0.2 parallelizer.resize(2) - parallelizer.num_threads.should == 2 - elapsed_time.should < 0.2 + expect(parallelizer.num_threads).to eq(2) + expect(elapsed_time).to be < 0.2 sleep(0.3) - @occupying_job_finished.should == [ true ] + expect(@occupying_job_finished).to eq([ true ]) end end @@ -276,9 +276,9 @@ describe Chef::ChefFS::Parallelizer do sleep(0.05) # Just enough to yield and get other inputs in the queue x end - enum.count.should == 6 - outputs_processed.should == 0 - input_mapper.num_processed.should == 6 + expect(enum.count).to eq(6) + expect(outputs_processed).to eq(0) + expect(input_mapper.num_processed).to eq(6) end it ".count with arguments works normally" do @@ -288,10 +288,10 @@ describe Chef::ChefFS::Parallelizer do outputs_processed += 1 x end - enum.count { |x| x > 1 }.should == 6 - enum.count(2).should == 3 - outputs_processed.should == 20 - input_mapper.num_processed.should == 20 + expect(enum.count { |x| x > 1 }).to eq(6) + expect(enum.count(2)).to eq(3) + expect(outputs_processed).to eq(20) + expect(input_mapper.num_processed).to eq(20) end it ".first does not enumerate anything other than the first result(s)" do @@ -302,10 +302,10 @@ describe Chef::ChefFS::Parallelizer do sleep(0.05) # Just enough to yield and get other inputs in the queue x end - enum.first.should == 1 - enum.first(2).should == [1,2] - outputs_processed.should == 3 - input_mapper.num_processed.should == 3 + expect(enum.first).to eq(1) + expect(enum.first(2)).to eq([1,2]) + expect(outputs_processed).to eq(3) + expect(input_mapper.num_processed).to eq(3) end it ".take does not enumerate anything other than the first result(s)" do @@ -316,9 +316,9 @@ describe Chef::ChefFS::Parallelizer do sleep(0.05) # Just enough to yield and get other inputs in the queue x end - enum.take(2).should == [1,2] - outputs_processed.should == 2 - input_mapper.num_processed.should == 2 + expect(enum.take(2)).to eq([1,2]) + expect(outputs_processed).to eq(2) + expect(input_mapper.num_processed).to eq(2) end it ".drop does not process anything other than the last result(s)" do @@ -329,9 +329,9 @@ describe Chef::ChefFS::Parallelizer do sleep(0.05) # Just enough to yield and get other inputs in the queue x end - enum.drop(2).should == [3,4,5,6] - outputs_processed.should == 4 - input_mapper.num_processed.should == 6 + expect(enum.drop(2)).to eq([3,4,5,6]) + expect(outputs_processed).to eq(4) + expect(input_mapper.num_processed).to eq(6) end if Enumerable.method_defined?(:lazy) @@ -343,9 +343,9 @@ describe Chef::ChefFS::Parallelizer do sleep(0.05) # Just enough to yield and get other inputs in the queue x end - enum.lazy.take(2).to_a.should == [1,2] - outputs_processed.should == 2 - input_mapper.num_processed.should == 2 + expect(enum.lazy.take(2).to_a).to eq([1,2]) + expect(outputs_processed).to eq(2) + expect(input_mapper.num_processed).to eq(2) end it ".drop does not process anything other than the last result(s)" do @@ -356,9 +356,9 @@ describe Chef::ChefFS::Parallelizer do sleep(0.05) # Just enough to yield and get other inputs in the queue x end - enum.lazy.drop(2).to_a.should == [3,4,5,6] - outputs_processed.should == 4 - input_mapper.num_processed.should == 6 + expect(enum.lazy.drop(2).to_a).to eq([3,4,5,6]) + expect(outputs_processed).to eq(4) + expect(input_mapper.num_processed).to eq(6) end it "lazy enumerable is actually lazy" do @@ -372,8 +372,8 @@ describe Chef::ChefFS::Parallelizer do enum.lazy.take(2) enum.lazy.drop(2) sleep(0.1) - outputs_processed.should == 0 - input_mapper.num_processed.should == 0 + expect(outputs_processed).to eq(0) + expect(input_mapper.num_processed).to eq(0) end end end @@ -386,10 +386,10 @@ describe Chef::ChefFS::Parallelizer do outputs_processed += 1 x end - enum.map { |x| x }.should == [1,2,3] - enum.map { |x| x }.should == [1,2,3] - outputs_processed.should == 6 - input_mapper.num_processed.should == 6 + expect(enum.map { |x| x }).to eq([1,2,3]) + expect(enum.map { |x| x }).to eq([1,2,3]) + expect(outputs_processed).to eq(6) + expect(input_mapper.num_processed).to eq(6) end it ".first and then .map on the same parallel enumerable returns the correct results and re-processes the input" do @@ -399,10 +399,10 @@ describe Chef::ChefFS::Parallelizer do outputs_processed += 1 x end - enum.first.should == 1 - enum.map { |x| x }.should == [1,2,3] - outputs_processed.should >= 4 - input_mapper.num_processed.should >= 4 + expect(enum.first).to eq(1) + expect(enum.map { |x| x }).to eq([1,2,3]) + expect(outputs_processed).to be >= 4 + expect(input_mapper.num_processed).to be >= 4 end it "two simultaneous enumerations throws an exception" do @@ -424,7 +424,7 @@ describe Chef::ChefFS::Parallelizer do context "And main_thread_processing on" do it "succeeds in running" do - parallelizer.parallelize([0.5]) { |x| x*2 }.to_a.should == [1] + expect(parallelizer.parallelize([0.5]) { |x| x*2 }.to_a).to eq([1]) end end end @@ -435,11 +435,11 @@ describe Chef::ChefFS::Parallelizer do end it "does not have contention issues with large numbers of inputs" do - parallelizer.parallelize(1.upto(500)) { |x| x+1 }.to_a.should == 2.upto(501).to_a + expect(parallelizer.parallelize(1.upto(500)) { |x| x+1 }.to_a).to eq(2.upto(501).to_a) end it "does not have contention issues with large numbers of inputs with ordering off" do - parallelizer.parallelize(1.upto(500), :ordered => false) { |x| x+1 }.to_a.sort.should == 2.upto(501).to_a + expect(parallelizer.parallelize(1.upto(500), :ordered => false) { |x| x+1 }.to_a.sort).to eq(2.upto(501).to_a) end it "does not have contention issues with large numbers of jobs and inputs with ordering off" do @@ -451,7 +451,7 @@ describe Chef::ChefFS::Parallelizer do Thread.new { outputs[i] = parallelizers[i].to_a } end threads.each { |thread| thread.join } - outputs.each { |output| output.sort.should == 2.upto(501).to_a } + outputs.each { |output| expect(output.sort).to eq(2.upto(501).to_a) } end end diff --git a/spec/unit/chef_spec.rb b/spec/unit/chef_spec.rb index b0f0359806..8a8d6c6c68 100644 --- a/spec/unit/chef_spec.rb +++ b/spec/unit/chef_spec.rb @@ -20,6 +20,6 @@ require 'spec_helper' describe Chef do it "should have a version defined" do - Chef::VERSION.should match(/(\d+)\.(\d+)\.(\d+)/) + expect(Chef::VERSION).to match(/(\d+)\.(\d+)\.(\d+)/) end end diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb index e03773ae03..10958d628c 100644 --- a/spec/unit/client_spec.rb +++ b/spec/unit/client_spec.rb @@ -44,7 +44,7 @@ describe Chef::Client do ohai_system = double( "Ohai::System", :all_plugins => true, :data => ohai_data) - ohai_system.stub(:[]) do |key| + allow(ohai_system).to receive(:[]) do |key| ohai_data[key] end ohai_system @@ -72,7 +72,7 @@ describe Chef::Client do # Node/Ohai data #Chef::Config[:node_name] = fqdn - Ohai::System.stub(:new).and_return(ohai_system) + allow(Ohai::System).to receive(:new).and_return(ohai_system) end describe "authentication protocol selection" do @@ -85,7 +85,7 @@ describe Chef::Client do Chef::Config[:node_name] = ("f" * 90) # ugly that this happens as a side effect of a getter :( client.node_name - Chef::Config[:authentication_protocol_version].should == "1.0" + expect(Chef::Config[:authentication_protocol_version]).to eq("1.0") end end @@ -94,7 +94,7 @@ describe Chef::Client do Chef::Config[:node_name] = ("f" * 91) # ugly that this happens as a side effect of a getter :( client.node_name - Chef::Config[:authentication_protocol_version].should == "1.1" + expect(Chef::Config[:authentication_protocol_version]).to eq("1.1") end end end @@ -104,11 +104,11 @@ describe Chef::Client do context "and STDOUT is a TTY" do before do - STDOUT.stub(:tty?).and_return(true) + allow(STDOUT).to receive(:tty?).and_return(true) end it "configures the :doc formatter" do - client.formatters_for_run.should == [[:doc]] + expect(client.formatters_for_run).to eq([[:doc]]) end context "and force_logger is set" do @@ -117,8 +117,8 @@ describe Chef::Client do end it "configures the :null formatter" do - Chef::Config[:force_logger].should be_true - client.formatters_for_run.should == [[:null]] + expect(Chef::Config[:force_logger]).to be_truthy + expect(client.formatters_for_run).to eq([[:null]]) end end @@ -127,11 +127,11 @@ describe Chef::Client do context "and STDOUT is not a TTY" do before do - STDOUT.stub(:tty?).and_return(false) + allow(STDOUT).to receive(:tty?).and_return(false) end it "configures the :null formatter" do - client.formatters_for_run.should == [[:null]] + expect(client.formatters_for_run).to eq([[:null]]) end context "and force_formatter is set" do @@ -139,7 +139,7 @@ describe Chef::Client do Chef::Config[:force_formatter] = true end it "it configures the :doc formatter" do - client.formatters_for_run.should == [[:doc]] + expect(client.formatters_for_run).to eq([[:doc]]) end end end @@ -153,14 +153,14 @@ describe Chef::Client do end it "does not configure a default formatter" do - client.formatters_for_run.should == [[:min, nil]] + expect(client.formatters_for_run).to eq([[:min, nil]]) end it "configures the formatter for STDOUT/STDERR" do configured_formatters = client.configure_formatters min_formatter = configured_formatters[0] - min_formatter.output.out.should == STDOUT - min_formatter.output.err.should == STDERR + expect(min_formatter.output.out).to eq(STDOUT) + expect(min_formatter.output.err).to eq(STDERR) end end @@ -178,8 +178,8 @@ describe Chef::Client do it "configures the formatter for the file path" do configured_formatters = client.configure_formatters min_formatter = configured_formatters[0] - min_formatter.output.out.path.should == @tmpout.path - min_formatter.output.err.path.should == @tmpout.path + expect(min_formatter.output.out.path).to eq(@tmpout.path) + expect(min_formatter.output.err.path).to eq(@tmpout.path) end end @@ -204,11 +204,11 @@ describe Chef::Client do # --Client.register # Make sure Client#register thinks the client key doesn't # exist, so it tries to register and create one. - File.should_receive(:exists?).with(Chef::Config[:client_key]).exactly(1).times.and_return(api_client_exists?) + expect(File).to receive(:exists?).with(Chef::Config[:client_key]).exactly(1).times.and_return(api_client_exists?) unless api_client_exists? # Client.register will register with the validation client name. - Chef::ApiClient::Registration.any_instance.should_receive(:run) + expect_any_instance_of(Chef::ApiClient::Registration).to receive(:run) end end @@ -216,59 +216,59 @@ describe Chef::Client do # Client.register will then turn around create another # Chef::REST object, this time with the client key it got from the # previous step. - Chef::REST.should_receive(:new). + expect(Chef::REST).to receive(:new). with(Chef::Config[:chef_server_url], fqdn, Chef::Config[:client_key]). exactly(1). and_return(http_node_load) # --Client#build_node # looks up the node, which we will return, then later saves it. - Chef::Node.should_receive(:find_or_create).with(fqdn).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(fqdn).and_return(node) # --ResourceReporter#node_load_completed # gets a run id from the server for storing resource history # (has its own tests, so stubbing it here.) - Chef::ResourceReporter.any_instance.should_receive(:node_load_completed) + expect_any_instance_of(Chef::ResourceReporter).to receive(:node_load_completed) end def stub_for_sync_cookbooks # --Client#setup_run_context # ---Client#sync_cookbooks -- downloads the list of cookbooks to sync # - Chef::CookbookSynchronizer.any_instance.should_receive(:sync_cookbooks) - Chef::REST.should_receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) - http_cookbook_sync.should_receive(:post). + expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) + expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) + expect(http_cookbook_sync).to receive(:post). with("environments/_default/cookbook_versions", {:run_list => []}). and_return({}) end def stub_for_converge # --Client#converge - Chef::Runner.should_receive(:new).and_return(runner) - runner.should_receive(:converge).and_return(true) + expect(Chef::Runner).to receive(:new).and_return(runner) + expect(runner).to receive(:converge).and_return(true) # --ResourceReporter#run_completed # updates the server with the resource history # (has its own tests, so stubbing it here.) - Chef::ResourceReporter.any_instance.should_receive(:run_completed) + expect_any_instance_of(Chef::ResourceReporter).to receive(:run_completed) end def stub_for_node_save - node.stub(:data_for_save).and_return(node.for_json) + allow(node).to receive(:data_for_save).and_return(node.for_json) # --Client#save_updated_node - Chef::REST.should_receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_node_save) - http_node_save.should_receive(:put_rest).with("nodes/#{fqdn}", node.for_json).and_return(true) + expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_node_save) + expect(http_node_save).to receive(:put_rest).with("nodes/#{fqdn}", node.for_json).and_return(true) end def stub_for_run - Chef::RunLock.any_instance.should_receive(:acquire) - Chef::RunLock.any_instance.should_receive(:save_pid) - Chef::RunLock.any_instance.should_receive(:release) + expect_any_instance_of(Chef::RunLock).to receive(:acquire) + expect_any_instance_of(Chef::RunLock).to receive(:save_pid) + expect_any_instance_of(Chef::RunLock).to receive(:release) # Post conditions: check that node has been filled in correctly - client.should_receive(:run_started) - client.should_receive(:run_completed_successfully) + expect(client).to receive(:run_started) + expect(client).to receive(:run_completed_successfully) end before do @@ -291,8 +291,8 @@ describe Chef::Client do client.run # fork is stubbed, so we can see the outcome of the run - node.automatic_attrs[:platform].should == "example-platform" - node.automatic_attrs[:platform_version].should == "example-platform-1.0" + expect(node.automatic_attrs[:platform]).to eq("example-platform") + expect(node.automatic_attrs[:platform_version]).to eq("example-platform-1.0") end end @@ -321,23 +321,23 @@ describe Chef::Client do before do # Client will try to compile and run override_recipe - Chef::RunContext::CookbookCompiler.any_instance.should_receive(:compile) + expect_any_instance_of(Chef::RunContext::CookbookCompiler).to receive(:compile) end def stub_for_sync_cookbooks # --Client#setup_run_context # ---Client#sync_cookbooks -- downloads the list of cookbooks to sync # - Chef::CookbookSynchronizer.any_instance.should_receive(:sync_cookbooks) - Chef::REST.should_receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) - http_cookbook_sync.should_receive(:post). + expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) + expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) + expect(http_cookbook_sync).to receive(:post). with("environments/_default/cookbook_versions", {:run_list => ["override_recipe"]}). and_return({}) end def stub_for_node_save # Expect NO node save - node.should_not_receive(:save) + expect(node).not_to receive(:save) end end end @@ -354,9 +354,9 @@ describe Chef::Client do # --Client#setup_run_context # ---Client#sync_cookbooks -- downloads the list of cookbooks to sync # - Chef::CookbookSynchronizer.any_instance.should_receive(:sync_cookbooks) - Chef::REST.should_receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) - http_cookbook_sync.should_receive(:post). + expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) + expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) + expect(http_cookbook_sync).to receive(:post). with("environments/_default/cookbook_versions", {:run_list => ["new_run_list_recipe"]}). and_return({}) end @@ -364,12 +364,12 @@ describe Chef::Client do before do # Client will try to compile and run the new_run_list_recipe, but we # do not create a fixture for this. - Chef::RunContext::CookbookCompiler.any_instance.should_receive(:compile) + expect_any_instance_of(Chef::RunContext::CookbookCompiler).to receive(:compile) end it "sets the new run list on the node" do client.run - node.run_list.should == Chef::RunList.new(new_runlist) + expect(node.run_list).to eq(Chef::RunList.new(new_runlist)) end end end @@ -381,23 +381,23 @@ describe Chef::Client do it "should remove the run_lock on failure of #load_node" do @run_lock = double("Chef::RunLock", :acquire => true) - Chef::RunLock.stub(:new).and_return(@run_lock) + allow(Chef::RunLock).to receive(:new).and_return(@run_lock) @events = double("Chef::EventDispatch::Dispatcher").as_null_object - Chef::EventDispatch::Dispatcher.stub(:new).and_return(@events) + allow(Chef::EventDispatch::Dispatcher).to receive(:new).and_return(@events) # @events is created on Chef::Client.new, so we need to recreate it after mocking client = Chef::Client.new - client.stub(:load_node).and_raise(Exception) - @run_lock.should_receive(:release) - lambda { client.run }.should raise_error(Exception) + allow(client).to receive(:load_node).and_raise(Exception) + expect(@run_lock).to receive(:release) + expect { client.run }.to raise_error(Exception) end end describe "when notifying other objects of the status of the chef run" do before do Chef::Client.clear_notifications - Chef::Node.stub(:find_or_create).and_return(node) - node.stub(:save) + allow(Chef::Node).to receive(:find_or_create).and_return(node) + allow(node).to receive(:save) client.load_node client.build_node end @@ -405,34 +405,34 @@ describe Chef::Client do it "notifies observers that the run has started" do notified = false Chef::Client.when_run_starts do |run_status| - run_status.node.should == node + expect(run_status.node).to eq(node) notified = true end client.run_started - notified.should be_true + expect(notified).to be_truthy end it "notifies observers that the run has completed successfully" do notified = false Chef::Client.when_run_completes_successfully do |run_status| - run_status.node.should == node + expect(run_status.node).to eq(node) notified = true end client.run_completed_successfully - notified.should be_true + expect(notified).to be_truthy end it "notifies observers that the run failed" do notified = false Chef::Client.when_run_fails do |run_status| - run_status.node.should == node + expect(run_status.node).to eq(node) notified = true end client.run_failed - notified.should be_true + expect(notified).to be_truthy end end @@ -446,73 +446,73 @@ describe Chef::Client do # build_node will call Node#expand! with server, which will # eventually hit the server to expand the included role. mock_chef_rest = double("Chef::REST") - mock_chef_rest.should_receive(:get_rest).with("roles/role_containing_cookbook1").and_return(role_containing_cookbook1) - Chef::REST.should_receive(:new).and_return(mock_chef_rest) + expect(mock_chef_rest).to receive(:get_rest).with("roles/role_containing_cookbook1").and_return(role_containing_cookbook1) + expect(Chef::REST).to receive(:new).and_return(mock_chef_rest) # check pre-conditions. - node[:roles].should be_nil - node[:recipes].should be_nil + expect(node[:roles]).to be_nil + expect(node[:recipes]).to be_nil - client.policy_builder.stub(:node).and_return(node) + allow(client.policy_builder).to receive(:node).and_return(node) # chefspec and possibly others use the return value of this method - client.build_node.should == node + expect(client.build_node).to eq(node) # check post-conditions. - node[:roles].should_not be_nil - node[:roles].length.should == 1 - node[:roles].should include("role_containing_cookbook1") - node[:recipes].should_not be_nil - node[:recipes].length.should == 1 - node[:recipes].should include("cookbook1") + expect(node[:roles]).not_to be_nil + expect(node[:roles].length).to eq(1) + expect(node[:roles]).to include("role_containing_cookbook1") + expect(node[:recipes]).not_to be_nil + expect(node[:recipes].length).to eq(1) + expect(node[:recipes]).to include("cookbook1") end it "should set the environment from the specified configuration value" do - node.chef_environment.should == "_default" + expect(node.chef_environment).to eq("_default") Chef::Config[:environment] = "A" test_env = Chef::Environment.new test_env.name("A") mock_chef_rest = double("Chef::REST") - mock_chef_rest.should_receive(:get_rest).with("environments/A").and_return(test_env) - Chef::REST.should_receive(:new).and_return(mock_chef_rest) - client.policy_builder.stub(:node).and_return(node) - client.build_node.should == node + expect(mock_chef_rest).to receive(:get_rest).with("environments/A").and_return(test_env) + expect(Chef::REST).to receive(:new).and_return(mock_chef_rest) + allow(client.policy_builder).to receive(:node).and_return(node) + expect(client.build_node).to eq(node) - node.chef_environment.should == "A" + expect(node.chef_environment).to eq("A") end end describe "windows_admin_check" do context "platform is not windows" do before do - Chef::Platform.stub(:windows?).and_return(false) + allow(Chef::Platform).to receive(:windows?).and_return(false) end it "shouldn't be called" do - client.should_not_receive(:has_admin_privileges?) + expect(client).not_to receive(:has_admin_privileges?) client.do_windows_admin_check end end context "platform is windows" do before do - Chef::Platform.stub(:windows?).and_return(true) + allow(Chef::Platform).to receive(:windows?).and_return(true) end it "should be called" do - client.should_receive(:has_admin_privileges?) + expect(client).to receive(:has_admin_privileges?) client.do_windows_admin_check end context "admin privileges exist" do before do - client.should_receive(:has_admin_privileges?).and_return(true) + expect(client).to receive(:has_admin_privileges?).and_return(true) end it "should not log a warning message" do - Chef::Log.should_not_receive(:warn) + expect(Chef::Log).not_to receive(:warn) client.do_windows_admin_check end @@ -525,11 +525,11 @@ describe Chef::Client do context "admin privileges doesn't exist" do before do - client.should_receive(:has_admin_privileges?).and_return(false) + expect(client).to receive(:has_admin_privileges?).and_return(false) end it "should log a warning message" do - Chef::Log.should_receive(:warn) + expect(Chef::Log).to receive(:warn) client.do_windows_admin_check end diff --git a/spec/unit/config_fetcher_spec.rb b/spec/unit/config_fetcher_spec.rb index 31787a0909..1b4a4903a8 100644 --- a/spec/unit/config_fetcher_spec.rb +++ b/spec/unit/config_fetcher_spec.rb @@ -16,10 +16,10 @@ describe Chef::ConfigFetcher do let(:config_content) { "# The client.rb content" } it "reads the file from disk" do - ::File.should_receive(:read). + expect(::File).to receive(:read). with(config_location). and_return(config_content) - fetcher.read_config.should == config_content + expect(fetcher.read_config).to eq(config_content) end context "and consuming JSON" do @@ -28,11 +28,11 @@ describe Chef::ConfigFetcher do it "returns the parsed JSON" do - ::File.should_receive(:read). + expect(::File).to receive(:read). with(config_location). and_return(valid_json) - fetcher.fetch_json.should == {"a" => "b"} + expect(fetcher.fetch_json).to eq({"a" => "b"}) end context "and the JSON is invalid" do @@ -40,11 +40,11 @@ describe Chef::ConfigFetcher do it "reports the JSON error" do - ::File.should_receive(:read). + expect(::File).to receive(:read). with(config_location). and_return(invalid_json) - Chef::Application.should_receive(:fatal!). + expect(Chef::Application).to receive(:fatal!). with(invalid_json_error_regex, 2) fetcher.fetch_json end @@ -59,32 +59,32 @@ describe Chef::ConfigFetcher do let(:config_content) { "# The client.rb content" } before do - Chef::HTTP::Simple.should_receive(:new). + expect(Chef::HTTP::Simple).to receive(:new). with(config_location). and_return(http) end it "reads the file over HTTP" do - http.should_receive(:get). + expect(http).to receive(:get). with("").and_return(config_content) - fetcher.read_config.should == config_content + expect(fetcher.read_config).to eq(config_content) end context "and consuming JSON" do let(:config_location) { "https://example.com/foo.json" } it "fetches the file and parses it" do - http.should_receive(:get). + expect(http).to receive(:get). with("").and_return(valid_json) - fetcher.fetch_json.should == {"a" => "b"} + expect(fetcher.fetch_json).to eq({"a" => "b"}) end context "and the JSON is invalid" do it "reports the JSON error" do - http.should_receive(:get). + expect(http).to receive(:get). with("").and_return(invalid_json) - Chef::Application.should_receive(:fatal!). + expect(Chef::Application).to receive(:fatal!). with(invalid_json_error_regex, 2) fetcher.fetch_json end diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index cc83ca3c45..fb782da2c7 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -28,7 +28,7 @@ describe Chef::Config do end it "sets the server url" do - Chef::Config.chef_server_url.should == "https://junglist.gen.nz" + expect(Chef::Config.chef_server_url).to eq("https://junglist.gen.nz") end context "when the url has a leading space" do @@ -37,7 +37,7 @@ describe Chef::Config do end it "strips the space from the url when setting" do - Chef::Config.chef_server_url.should == "https://junglist.gen.nz" + expect(Chef::Config.chef_server_url).to eq("https://junglist.gen.nz") end end @@ -48,7 +48,7 @@ describe Chef::Config do end it "strips the space from the url when setting without raising an error" do - Chef::Config.chef_server_url.should == "https://junglist.gen.nz" + expect(Chef::Config.chef_server_url).to eq("https://junglist.gen.nz") end end @@ -79,39 +79,39 @@ describe Chef::Config do # end # it "has an empty list of formatters by default" do - Chef::Config.formatters.should == [] + expect(Chef::Config.formatters).to eq([]) end it "configures a formatter with a short name" do Chef::Config.add_formatter(:doc) - Chef::Config.formatters.should == [[:doc, nil]] + expect(Chef::Config.formatters).to eq([[:doc, nil]]) end it "configures a formatter with a file output" do Chef::Config.add_formatter(:doc, "/var/log/formatter.log") - Chef::Config.formatters.should == [[:doc, "/var/log/formatter.log"]] + expect(Chef::Config.formatters).to eq([[:doc, "/var/log/formatter.log"]]) end end describe "class method: manage_secret_key" do before do - Chef::FileCache.stub(:load).and_return(true) - Chef::FileCache.stub(:has_key?).with("chef_server_cookie_id").and_return(false) + allow(Chef::FileCache).to receive(:load).and_return(true) + allow(Chef::FileCache).to receive(:has_key?).with("chef_server_cookie_id").and_return(false) end it "should generate and store a chef server cookie id" do - Chef::FileCache.should_receive(:store).with("chef_server_cookie_id", /\w{40}/).and_return(true) + expect(Chef::FileCache).to receive(:store).with("chef_server_cookie_id", /\w{40}/).and_return(true) Chef::Config.manage_secret_key end describe "when the filecache has a chef server cookie id key" do before do - Chef::FileCache.stub(:has_key?).with("chef_server_cookie_id").and_return(true) + allow(Chef::FileCache).to receive(:has_key?).with("chef_server_cookie_id").and_return(true) end it "should not generate and store a chef server cookie id" do - Chef::FileCache.should_not_receive(:store).with("chef_server_cookie_id", /\w{40}/) + expect(Chef::FileCache).not_to receive(:store).with("chef_server_cookie_id", /\w{40}/) Chef::Config.manage_secret_key end end @@ -126,23 +126,23 @@ describe Chef::Config do end before :each do - Chef::Platform.stub(:windows?).and_return(is_windows) + allow(Chef::Platform).to receive(:windows?).and_return(is_windows) end describe "class method: platform_specific_path" do if is_windows it "should return a windows path on windows systems" do path = "/etc/chef/cookbooks" - Chef::Config.stub(:env).and_return({ 'SYSTEMDRIVE' => 'C:' }) + allow(Chef::Config).to receive(:env).and_return({ 'SYSTEMDRIVE' => 'C:' }) # match on a regex that looks for the base path with an optional # system drive at the beginning (c:) # system drive is not hardcoded b/c it can change and b/c it is not present on linux systems - Chef::Config.platform_specific_path(path).should == "C:\\chef\\cookbooks" + expect(Chef::Config.platform_specific_path(path)).to eq("C:\\chef\\cookbooks") end else it "should return given path on non-windows systems" do path = "/etc/chef/cookbooks" - Chef::Config.platform_specific_path(path).should == "/etc/chef/cookbooks" + expect(Chef::Config.platform_specific_path(path)).to eq("/etc/chef/cookbooks") end end end @@ -166,46 +166,46 @@ describe Chef::Config do before do if is_windows - Chef::Config.stub(:env).and_return({ 'SYSTEMDRIVE' => 'C:' }) + allow(Chef::Config).to receive(:env).and_return({ 'SYSTEMDRIVE' => 'C:' }) Chef::Config[:user_home] = 'C:\Users\charlie' else Chef::Config[:user_home] = '/Users/charlie' end - Chef::Config.stub(:path_accessible?).and_return(false) + allow(Chef::Config).to receive(:path_accessible?).and_return(false) end describe "Chef::Config[:cache_path]" do context "when /var/chef exists and is accessible" do it "defaults to /var/chef" do - Chef::Config.stub(:path_accessible?).with(to_platform("/var/chef")).and_return(true) - Chef::Config[:cache_path].should == primary_cache_path + allow(Chef::Config).to receive(:path_accessible?).with(to_platform("/var/chef")).and_return(true) + expect(Chef::Config[:cache_path]).to eq(primary_cache_path) end end context "when /var/chef does not exist and /var is accessible" do it "defaults to /var/chef" do - File.stub(:exists?).with(to_platform("/var/chef")).and_return(false) - Chef::Config.stub(:path_accessible?).with(to_platform("/var")).and_return(true) - Chef::Config[:cache_path].should == primary_cache_path + allow(File).to receive(:exists?).with(to_platform("/var/chef")).and_return(false) + allow(Chef::Config).to receive(:path_accessible?).with(to_platform("/var")).and_return(true) + expect(Chef::Config[:cache_path]).to eq(primary_cache_path) end end context "when /var/chef does not exist and /var is not accessible" do it "defaults to $HOME/.chef" do - File.stub(:exists?).with(to_platform("/var/chef")).and_return(false) - Chef::Config.stub(:path_accessible?).with(to_platform("/var")).and_return(false) - Chef::Config[:cache_path].should == secondary_cache_path + allow(File).to receive(:exists?).with(to_platform("/var/chef")).and_return(false) + allow(Chef::Config).to receive(:path_accessible?).with(to_platform("/var")).and_return(false) + expect(Chef::Config[:cache_path]).to eq(secondary_cache_path) end end context "when /var/chef exists and is not accessible" do it "defaults to $HOME/.chef" do - File.stub(:exists?).with(to_platform("/var/chef")).and_return(true) - File.stub(:readable?).with(to_platform("/var/chef")).and_return(true) - File.stub(:writable?).with(to_platform("/var/chef")).and_return(false) + allow(File).to receive(:exists?).with(to_platform("/var/chef")).and_return(true) + allow(File).to receive(:readable?).with(to_platform("/var/chef")).and_return(true) + allow(File).to receive(:writable?).with(to_platform("/var/chef")).and_return(false) - Chef::Config[:cache_path].should == secondary_cache_path + expect(Chef::Config[:cache_path]).to eq(secondary_cache_path) end end @@ -220,7 +220,7 @@ describe Chef::Config do end it "cache_path is /a/b/c/local-mode-cache" do - Chef::Config.cache_path.should == to_platform('/a/b/c/local-mode-cache') + expect(Chef::Config.cache_path).to eq(to_platform('/a/b/c/local-mode-cache')) end end @@ -230,43 +230,43 @@ describe Chef::Config do end it "cache_path is /a/b/c/local-mode-cache" do - Chef::Config.cache_path.should == to_platform('/a/b/c/local-mode-cache') + expect(Chef::Config.cache_path).to eq(to_platform('/a/b/c/local-mode-cache')) end end end end it "Chef::Config[:file_backup_path] defaults to /var/chef/backup" do - Chef::Config.stub(:cache_path).and_return(primary_cache_path) + allow(Chef::Config).to receive(:cache_path).and_return(primary_cache_path) backup_path = is_windows ? "#{primary_cache_path}\\backup" : "#{primary_cache_path}/backup" - Chef::Config[:file_backup_path].should == backup_path + expect(Chef::Config[:file_backup_path]).to eq(backup_path) end it "Chef::Config[:ssl_verify_mode] defaults to :verify_peer" do - Chef::Config[:ssl_verify_mode].should == :verify_peer + expect(Chef::Config[:ssl_verify_mode]).to eq(:verify_peer) end it "Chef::Config[:ssl_ca_path] defaults to nil" do - Chef::Config[:ssl_ca_path].should be_nil + expect(Chef::Config[:ssl_ca_path]).to be_nil end # TODO can this be removed? if !is_windows it "Chef::Config[:ssl_ca_file] defaults to nil" do - Chef::Config[:ssl_ca_file].should be_nil + expect(Chef::Config[:ssl_ca_file]).to be_nil end end it "Chef::Config[:data_bag_path] defaults to /var/chef/data_bags" do - Chef::Config.stub(:cache_path).and_return(primary_cache_path) + allow(Chef::Config).to receive(:cache_path).and_return(primary_cache_path) data_bag_path = is_windows ? "#{primary_cache_path}\\data_bags" : "#{primary_cache_path}/data_bags" - Chef::Config[:data_bag_path].should == data_bag_path + expect(Chef::Config[:data_bag_path]).to eq(data_bag_path) end it "Chef::Config[:environment_path] defaults to /var/chef/environments" do - Chef::Config.stub(:cache_path).and_return(primary_cache_path) + allow(Chef::Config).to receive(:cache_path).and_return(primary_cache_path) environment_path = is_windows ? "#{primary_cache_path}\\environments" : "#{primary_cache_path}/environments" - Chef::Config[:environment_path].should == environment_path + expect(Chef::Config[:environment_path]).to eq(environment_path) end describe "setting the config dir" do @@ -278,7 +278,7 @@ describe Chef::Config do end it "config_dir is /etc/chef" do - Chef::Config.config_dir.should == to_platform("/etc/chef") + expect(Chef::Config.config_dir).to eq(to_platform("/etc/chef")) end context "and chef is running in local mode" do @@ -287,7 +287,7 @@ describe Chef::Config do end it "config_dir is /etc/chef" do - Chef::Config.config_dir.should == to_platform("/etc/chef") + expect(Chef::Config.config_dir).to eq(to_platform("/etc/chef")) end end @@ -297,7 +297,7 @@ describe Chef::Config do end it "yields the explicit value" do - Chef::Config.config_dir.should == to_platform("/other/config/dir/") + expect(Chef::Config.config_dir).to eq(to_platform("/other/config/dir/")) end end @@ -309,7 +309,7 @@ describe Chef::Config do end it "config_dir is /home/charlie/.chef/" do - Chef::Config.config_dir.should == Chef::Util::PathHelper.join(to_platform("/home/charlie/.chef"), '') + expect(Chef::Config.config_dir).to eq(Chef::Util::PathHelper.join(to_platform("/home/charlie/.chef"), '')) end context "and chef is running in local mode" do @@ -318,7 +318,7 @@ describe Chef::Config do end it "config_dir is /home/charlie/.chef/" do - Chef::Config.config_dir.should == Chef::Util::PathHelper.join(to_platform("/home/charlie/.chef"), '') + expect(Chef::Config.config_dir).to eq(Chef::Util::PathHelper.join(to_platform("/home/charlie/.chef"), '')) end end end @@ -334,24 +334,24 @@ describe Chef::Config do let(:default_ca_file) { "c:/opscode/chef/embedded/ssl/certs/cacert.pem" } it "finds the embedded dir in the default location" do - Chef::Config.stub(:_this_file).and_return(default_config_location) - Chef::Config.embedded_dir.should == "c:/opscode/chef/embedded" + allow(Chef::Config).to receive(:_this_file).and_return(default_config_location) + expect(Chef::Config.embedded_dir).to eq("c:/opscode/chef/embedded") end it "finds the embedded dir in a custom install location" do - Chef::Config.stub(:_this_file).and_return(alternate_install_location) - Chef::Config.embedded_dir.should == "c:/my/alternate/install/place/chef/embedded" + allow(Chef::Config).to receive(:_this_file).and_return(alternate_install_location) + expect(Chef::Config.embedded_dir).to eq("c:/my/alternate/install/place/chef/embedded") end it "doesn't error when not in an omnibus install" do - Chef::Config.stub(:_this_file).and_return(non_omnibus_location) - Chef::Config.embedded_dir.should be_nil + allow(Chef::Config).to receive(:_this_file).and_return(non_omnibus_location) + expect(Chef::Config.embedded_dir).to be_nil end it "sets the ssl_ca_cert path if the cert file is available" do - Chef::Config.stub(:_this_file).and_return(default_config_location) - File.stub(:exist?).with(default_ca_file).and_return(true) - Chef::Config.ssl_ca_file.should == default_ca_file + allow(Chef::Config).to receive(:_this_file).and_return(default_config_location) + allow(File).to receive(:exist?).with(default_ca_file).and_return(true) + expect(Chef::Config.ssl_ca_file).to eq(default_ca_file) end end end @@ -360,19 +360,19 @@ describe Chef::Config do describe "Chef::Config[:user_home]" do it "should set when HOME is provided" do expected = to_platform("/home/kitten") - Chef::Config.stub(:env).and_return({ 'HOME' => expected }) - Chef::Config[:user_home].should == expected + allow(Chef::Config).to receive(:env).and_return({ 'HOME' => expected }) + expect(Chef::Config[:user_home]).to eq(expected) end it "should be set when only USERPROFILE is provided" do expected = to_platform("/users/kitten") - Chef::Config.stub(:env).and_return({ 'USERPROFILE' => expected }) - Chef::Config[:user_home].should == expected + allow(Chef::Config).to receive(:env).and_return({ 'USERPROFILE' => expected }) + expect(Chef::Config[:user_home]).to eq(expected) end it "falls back to the current working directory when HOME and USERPROFILE is not set" do - Chef::Config.stub(:env).and_return({}) - Chef::Config[:user_home].should == Dir.pwd + allow(Chef::Config).to receive(:env).and_return({}) + expect(Chef::Config[:user_home]).to eq(Dir.pwd) end end @@ -380,32 +380,32 @@ describe Chef::Config do let(:db_secret_default_path){ to_platform("/etc/chef/encrypted_data_bag_secret") } before do - File.stub(:exist?).with(db_secret_default_path).and_return(secret_exists) + allow(File).to receive(:exist?).with(db_secret_default_path).and_return(secret_exists) end context "/etc/chef/encrypted_data_bag_secret exists" do let(:secret_exists) { true } it "sets the value to /etc/chef/encrypted_data_bag_secret" do - Chef::Config[:encrypted_data_bag_secret].should eq db_secret_default_path + expect(Chef::Config[:encrypted_data_bag_secret]).to eq db_secret_default_path end end context "/etc/chef/encrypted_data_bag_secret does not exist" do let(:secret_exists) { false } it "sets the value to nil" do - Chef::Config[:encrypted_data_bag_secret].should be_nil + expect(Chef::Config[:encrypted_data_bag_secret]).to be_nil end end end describe "Chef::Config[:event_handlers]" do it "sets a event_handlers to an empty array by default" do - Chef::Config[:event_handlers].should eq([]) + expect(Chef::Config[:event_handlers]).to eq([]) end it "should be able to add custom handlers" do o = Object.new Chef::Config[:event_handlers] << o - Chef::Config[:event_handlers].should be_include(o) + expect(Chef::Config[:event_handlers]).to be_include(o) end end @@ -413,7 +413,7 @@ describe Chef::Config do context "on a platform that is not Windows" do it "allows one letter usernames" do any_match = Chef::Config[:user_valid_regex].any? { |regex| regex.match('a') } - expect(any_match).to be_true + expect(any_match).to be_truthy end end end diff --git a/spec/unit/cookbook/chefignore_spec.rb b/spec/unit/cookbook/chefignore_spec.rb index e529a6d05a..9f5546de28 100644 --- a/spec/unit/cookbook/chefignore_spec.rb +++ b/spec/unit/cookbook/chefignore_spec.rb @@ -23,18 +23,18 @@ describe Chef::Cookbook::Chefignore do end it "loads the globs in the chefignore file" do - @chefignore.ignores.should =~ %w[recipes/ignoreme.rb ignored] + expect(@chefignore.ignores).to match_array(%w[recipes/ignoreme.rb ignored]) end it "removes items from an array that match the ignores" do file_list = %w[ recipes/ignoreme.rb recipes/dontignoreme.rb ] - @chefignore.remove_ignores_from(file_list).should == %w[recipes/dontignoreme.rb] + expect(@chefignore.remove_ignores_from(file_list)).to eq(%w[recipes/dontignoreme.rb]) end it "determines if a file is ignored" do - @chefignore.ignored?('ignored').should be_true - @chefignore.ignored?('recipes/ignoreme.rb').should be_true - @chefignore.ignored?('recipes/dontignoreme.rb').should be_false + expect(@chefignore.ignored?('ignored')).to be_truthy + expect(@chefignore.ignored?('recipes/ignoreme.rb')).to be_truthy + expect(@chefignore.ignored?('recipes/dontignoreme.rb')).to be_falsey end context "when using the single cookbook pattern" do @@ -43,7 +43,7 @@ describe Chef::Cookbook::Chefignore do end it "loads the globs in the chefignore file" do - @chefignore.ignores.should =~ %w[recipes/ignoreme.rb ignored vendor/bundle/*] + expect(@chefignore.ignores).to match_array(%w[recipes/ignoreme.rb ignored vendor/bundle/*]) end end end diff --git a/spec/unit/cookbook/cookbook_version_loader_spec.rb b/spec/unit/cookbook/cookbook_version_loader_spec.rb index 4ba4e1de57..2c4ad11787 100644 --- a/spec/unit/cookbook/cookbook_version_loader_spec.rb +++ b/spec/unit/cookbook/cookbook_version_loader_spec.rb @@ -20,7 +20,7 @@ require 'spec_helper' describe Chef::Cookbook::CookbookVersionLoader do before do - Chef::Platform.stub(:windows?) { false } + allow(Chef::Platform).to receive(:windows?) { false } end describe "loading a cookbook" do @@ -74,8 +74,8 @@ describe Chef::Cookbook::CookbookVersionLoader do end it "should load the metadata for the cookbook" do - loaded_cookbook.metadata.name.to_s.should == "openldap" - loaded_cookbook.metadata.should be_a_kind_of(Chef::Cookbook::Metadata) + expect(loaded_cookbook.metadata.name.to_s).to eq("openldap") + expect(loaded_cookbook.metadata).to be_a_kind_of(Chef::Cookbook::Metadata) end context "when a cookbook has ignored files" do diff --git a/spec/unit/cookbook/metadata_spec.rb b/spec/unit/cookbook/metadata_spec.rb index 51814320d4..a1903a1948 100644 --- a/spec/unit/cookbook/metadata_spec.rb +++ b/spec/unit/cookbook/metadata_spec.rb @@ -34,7 +34,7 @@ describe Chef::Cookbook::Metadata do end it "does not depend on object identity for equality" do - metadata.should == metadata.dup + expect(metadata).to eq(metadata.dup) end it "is not equal to another object if it isn't have all of the metadata fields" do @@ -46,7 +46,7 @@ describe Chef::Cookbook::Metadata do setter = "#{field}=" metadata_value = metadata.send(field) almost_duck_type.send(setter, metadata_value) if almost_duck_type.respond_to?(setter) - @mets.should_not == almost_duck_type + expect(@mets).not_to eq(almost_duck_type) end end end @@ -58,7 +58,7 @@ describe Chef::Cookbook::Metadata do metadata_value = metadata.send(field) duck_type.send(setter, metadata_value) end - metadata.should == duck_type + expect(metadata).to eq(duck_type) end it "is not equal if any values are different" do @@ -73,7 +73,7 @@ describe Chef::Cookbook::Metadata do end duck_type.send("#{field_to_change}=".to_sym, :epic_fail) - metadata.should_not == duck_type + expect(metadata).not_to eq(duck_type) end end @@ -82,71 +82,71 @@ describe Chef::Cookbook::Metadata do describe "when first created" do it "has no name" do - metadata.name.should eq(nil) + expect(metadata.name).to eq(nil) end it "has an empty description" do - metadata.description.should eq("") + expect(metadata.description).to eq("") end it "has an empty long description" do - metadata.long_description.should eq("") + expect(metadata.long_description).to eq("") end it "defaults to 'all rights reserved' license" do - metadata.license.should eq("All rights reserved") + expect(metadata.license).to eq("All rights reserved") end it "has an empty maintainer field" do - metadata.maintainer.should eq(nil) + expect(metadata.maintainer).to eq(nil) end it "has an empty maintainer_email field" do - metadata.maintainer.should eq(nil) + expect(metadata.maintainer).to eq(nil) end it "has an empty platforms list" do - metadata.platforms.should eq(Mash.new) + expect(metadata.platforms).to eq(Mash.new) end it "has an empty dependencies list" do - metadata.dependencies.should eq(Mash.new) + expect(metadata.dependencies).to eq(Mash.new) end it "has an empty recommends list" do - metadata.recommendations.should eq(Mash.new) + expect(metadata.recommendations).to eq(Mash.new) end it "has an empty suggestions list" do - metadata.suggestions.should eq(Mash.new) + expect(metadata.suggestions).to eq(Mash.new) end it "has an empty conflicts list" do - metadata.conflicting.should eq(Mash.new) + expect(metadata.conflicting).to eq(Mash.new) end it "has an empty replaces list" do - metadata.replacing.should eq(Mash.new) + expect(metadata.replacing).to eq(Mash.new) end it "has an empty attributes list" do - metadata.attributes.should eq(Mash.new) + expect(metadata.attributes).to eq(Mash.new) end it "has an empty groupings list" do - metadata.groupings.should eq(Mash.new) + expect(metadata.groupings).to eq(Mash.new) end it "has an empty recipes list" do - metadata.recipes.should eq(Mash.new) + expect(metadata.recipes).to eq(Mash.new) end it "has an empty source_url string" do - metadata.source_url.should eq('') + expect(metadata.source_url).to eq('') end it "has an empty issues_url string" do - metadata.issues_url.should eq('') + expect(metadata.issues_url).to eq('') end end @@ -155,12 +155,12 @@ describe Chef::Cookbook::Metadata do context "when no required fields are set" do it "is not valid" do - metadata.should_not be_valid + expect(metadata).not_to be_valid end it "has a list of validation errors" do expected_errors = ["The `name' attribute is required in cookbook metadata"] - metadata.errors.should eq(expected_errors) + expect(metadata.errors).to eq(expected_errors) end end @@ -171,11 +171,11 @@ describe Chef::Cookbook::Metadata do end it "is valid" do - metadata.should be_valid + expect(metadata).to be_valid end it "has no validation errors" do - metadata.errors.should be_empty + expect(metadata.errors).to be_empty end end @@ -185,7 +185,7 @@ describe Chef::Cookbook::Metadata do describe "adding a supported platform" do it "should support adding a supported platform with a single expression" do metadata.supports("ubuntu", ">= 8.04") - metadata.platforms["ubuntu"].should == '>= 8.04' + expect(metadata.platforms["ubuntu"]).to eq('>= 8.04') end end @@ -203,23 +203,23 @@ describe Chef::Cookbook::Metadata do params.sort { |a,b| a.to_s <=> b.to_s }.each do |field, field_value| describe field do it "should be set-able via #{field}" do - metadata.send(field, field_value).should eql(field_value) + expect(metadata.send(field, field_value)).to eql(field_value) end it "should be get-able via #{field}" do metadata.send(field, field_value) - metadata.send(field).should eql(field_value) + expect(metadata.send(field)).to eql(field_value) end end end describe "version transformation" do it "should transform an '0.6' version to '0.6.0'" do - metadata.send(:version, "0.6").should eql("0.6.0") + expect(metadata.send(:version, "0.6")).to eql("0.6.0") end it "should spit out '0.6.0' after transforming '0.6'" do metadata.send(:version, "0.6") - metadata.send(:version).should eql("0.6.0") + expect(metadata.send(:version)).to eql("0.6.0") end end end @@ -238,11 +238,11 @@ describe Chef::Cookbook::Metadata do check_with = dep_args.shift describe dep do it "should be set-able via #{dep}" do - metadata.send(dep, *dep_args).should == dep_args[1] + expect(metadata.send(dep, *dep_args)).to eq(dep_args[1]) end it "should be get-able via #{check_with}" do metadata.send(dep, *dep_args) - metadata.send(check_with).should == { dep_args[0] => dep_args[1] } + expect(metadata.send(check_with)).to eq({ dep_args[0] => dep_args[1] }) end end end @@ -260,11 +260,11 @@ describe Chef::Cookbook::Metadata do normalized_version = dep_args.pop describe dep do it "should be set-able and normalized via #{dep}" do - metadata.send(dep, *dep_args).should == normalized_version + expect(metadata.send(dep, *dep_args)).to eq(normalized_version) end it "should be get-able and normalized via #{check_with}" do metadata.send(dep, *dep_args) - metadata.send(check_with).should == { dep_args[0] => normalized_version } + expect(metadata.send(check_with)).to eq({ dep_args[0] => normalized_version }) end end end @@ -282,7 +282,7 @@ describe Chef::Cookbook::Metadata do dep_types.each do |dep, dep_args| it "for #{dep} raises an informative error instead of vomiting on your shoes" do - lambda {metadata.send(dep, *dep_args)}.should raise_error(Chef::Exceptions::ObsoleteDependencySyntax) + expect {metadata.send(dep, *dep_args)}.to raise_error(Chef::Exceptions::ObsoleteDependencySyntax) end end end @@ -300,7 +300,7 @@ describe Chef::Cookbook::Metadata do dep_types.each do |dep, dep_args| it "for #{dep} raises an informative error instead of vomiting on your shoes" do - lambda {metadata.send(dep, *dep_args)}.should raise_error(Chef::Exceptions::InvalidVersionConstraint) + expect {metadata.send(dep, *dep_args)}.to raise_error(Chef::Exceptions::InvalidVersionConstraint) end end end @@ -312,24 +312,24 @@ describe Chef::Cookbook::Metadata do "title" => "MySQL Tuning", "description" => "Setting from the my.cnf file that allow you to tune your mysql server" } - metadata.grouping("/db/mysql/databases/tuning", group).should == group + expect(metadata.grouping("/db/mysql/databases/tuning", group)).to eq(group) end it "should not accept anything but a string for display_name" do - lambda { + expect { metadata.grouping("db/mysql/databases", :title => "foo") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.grouping("db/mysql/databases", :title => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should not accept anything but a string for the description" do - lambda { + expect { metadata.grouping("db/mysql/databases", :description => "foo") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.grouping("db/mysql/databases", :description => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end @@ -347,170 +347,170 @@ describe Chef::Cookbook::Metadata do "source_url" => "http://example.com", "issues_url" => "http://example.com/issues" } - metadata.attribute("/db/mysql/databases", attrs).should == attrs + expect(metadata.attribute("/db/mysql/databases", attrs)).to eq(attrs) end it "should not accept anything but a string for display_name" do - lambda { + expect { metadata.attribute("db/mysql/databases", :display_name => "foo") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :display_name => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should not accept anything but a string for the description" do - lambda { + expect { metadata.attribute("db/mysql/databases", :description => "foo") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :description => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should not accept anything but a string for the source_url" do - lambda { + expect { metadata.attribute("db/mysql/databases", :source_url => "foo") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :source_url => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should not accept anything but a string for the issues_url" do - lambda { + expect { metadata.attribute("db/mysql/databases", :issues_url => "foo") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :issues_url => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should not accept anything but an array of strings for choice" do - lambda { + expect { metadata.attribute("db/mysql/databases", :choice => ['dedicated', 'shared']) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :choice => [10, 'shared']) - }.should raise_error(ArgumentError) - lambda { + }.to raise_error(ArgumentError) + expect { metadata.attribute("db/mysql/databases", :choice => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should set choice to empty array by default" do metadata.attribute("db/mysql/databases", {}) - metadata.attributes["db/mysql/databases"][:choice].should == [] + expect(metadata.attributes["db/mysql/databases"][:choice]).to eq([]) end it "should let calculated be true or false" do - lambda { + expect { metadata.attribute("db/mysql/databases", :calculated => true) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :calculated => false) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :calculated => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should set calculated to false by default" do metadata.attribute("db/mysql/databases", {}) - metadata.attributes["db/mysql/databases"][:calculated].should == false + expect(metadata.attributes["db/mysql/databases"][:calculated]).to eq(false) end it "accepts String for the attribute type" do - lambda { + expect { metadata.attribute("db/mysql/databases", :type => "string") - }.should_not raise_error + }.not_to raise_error end it "accepts Array for the attribute type" do - lambda { + expect { metadata.attribute("db/mysql/databases", :type => "array") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :type => Array.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "accepts symbol for the attribute type" do - lambda { + expect { metadata.attribute("db/mysql/databases", :type => "symbol") - }.should_not raise_error + }.not_to raise_error end it "should let type be hash (backwards compatability only)" do - lambda { + expect { metadata.attribute("db/mysql/databases", :type => "hash") - }.should_not raise_error + }.not_to raise_error end it "should let required be required, recommended or optional" do - lambda { + expect { metadata.attribute("db/mysql/databases", :required => 'required') - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :required => 'recommended') - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :required => 'optional') - }.should_not raise_error + }.not_to raise_error end it "should convert required true to required" do - lambda { + expect { metadata.attribute("db/mysql/databases", :required => true) - }.should_not raise_error + }.not_to raise_error #attrib = metadata.attributes["db/mysql/databases"][:required].should == "required" end it "should convert required false to optional" do - lambda { + expect { metadata.attribute("db/mysql/databases", :required => false) - }.should_not raise_error + }.not_to raise_error #attrib = metadata.attributes["db/mysql/databases"][:required].should == "optional" end it "should set required to 'optional' by default" do metadata.attribute("db/mysql/databases", {}) - metadata.attributes["db/mysql/databases"][:required].should == 'optional' + expect(metadata.attributes["db/mysql/databases"][:required]).to eq('optional') end it "should make sure recipes is an array" do - lambda { + expect { metadata.attribute("db/mysql/databases", :recipes => []) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :required => Hash.new) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should set recipes to an empty array by default" do metadata.attribute("db/mysql/databases", {}) - metadata.attributes["db/mysql/databases"][:recipes].should == [] + expect(metadata.attributes["db/mysql/databases"][:recipes]).to eq([]) end it "should allow the default value to be a string, array, hash, boolean or numeric" do - lambda { + expect { metadata.attribute("db/mysql/databases", :default => []) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :default => {}) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :default => "alice in chains") - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :default => 1337) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :default => true) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { metadata.attribute("db/mysql/databases", :required => :not_gonna_do_it) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should limit the types allowed in the choice array" do @@ -519,87 +519,87 @@ describe Chef::Cookbook::Metadata do :choice => [ "test1", "test2" ], :default => "test1" } - lambda { + expect { metadata.attribute("test_cookbook/test", options) - }.should_not raise_error + }.not_to raise_error options = { :type => "boolean", :choice => [ true, false ], :default => true } - lambda { + expect { metadata.attribute("test_cookbook/test", options) - }.should_not raise_error + }.not_to raise_error options = { :type => "numeric", :choice => [ 1337, 420 ], :default => 1337 } - lambda { + expect { metadata.attribute("test_cookbook/test", options) - }.should_not raise_error + }.not_to raise_error options = { :type => "numeric", :choice => [ true, "false" ], :default => false } - lambda { + expect { metadata.attribute("test_cookbook/test", options) - }.should raise_error + }.to raise_error end it "should error if default used with calculated" do - lambda { + expect { attrs = { :calculated => true, :default => [ "I thought you said calculated" ] } metadata.attribute("db/mysql/databases", attrs) - }.should raise_error(ArgumentError) - lambda { + }.to raise_error(ArgumentError) + expect { attrs = { :calculated => true, :default => "I thought you said calculated" } metadata.attribute("db/mysql/databases", attrs) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should allow a default that is a choice" do - lambda { + expect { attrs = { :choice => [ "a", "b", "c"], :default => "b" } metadata.attribute("db/mysql/databases", attrs) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { attrs = { :choice => [ "a", "b", "c", "d", "e"], :default => ["b", "d"] } metadata.attribute("db/mysql/databases", attrs) - }.should_not raise_error + }.not_to raise_error end it "should error if default is not a choice" do - lambda { + expect { attrs = { :choice => [ "a", "b", "c"], :default => "d" } metadata.attribute("db/mysql/databases", attrs) - }.should raise_error(ArgumentError) - lambda { + }.to raise_error(ArgumentError) + expect { attrs = { :choice => [ "a", "b", "c", "d", "e"], :default => ["b", "z"] } metadata.attribute("db/mysql/databases", attrs) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end end @@ -616,18 +616,18 @@ describe Chef::Cookbook::Metadata do end it "should have the names of the recipes" do - metadata.recipes["test_cookbook"].should == "" - metadata.recipes["test_cookbook::enlighten"].should == "" + expect(metadata.recipes["test_cookbook"]).to eq("") + expect(metadata.recipes["test_cookbook::enlighten"]).to eq("") end it "should let you set the description for a recipe" do metadata.recipe "test_cookbook", "It, um... tests stuff?" - metadata.recipes["test_cookbook"].should == "It, um... tests stuff?" + expect(metadata.recipes["test_cookbook"]).to eq("It, um... tests stuff?") end it "should automatically provide each recipe" do - metadata.providing.has_key?("test_cookbook").should == true - metadata.providing.has_key?("test_cookbook::enlighten").should == true + expect(metadata.providing.has_key?("test_cookbook")).to eq(true) + expect(metadata.providing.has_key?("test_cookbook::enlighten")).to eq(true) end end @@ -662,7 +662,7 @@ describe Chef::Cookbook::Metadata do let(:deserialized_metadata) { Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(metadata)) } it "should serialize to a json hash" do - deserialized_metadata.should be_a_kind_of(Hash) + expect(deserialized_metadata).to be_a_kind_of(Hash) end %w{ @@ -686,7 +686,7 @@ describe Chef::Cookbook::Metadata do issues_url }.each do |t| it "should include '#{t}'" do - deserialized_metadata[t].should == metadata.send(t.to_sym) + expect(deserialized_metadata[t]).to eq(metadata.send(t.to_sym)) end end end @@ -697,7 +697,7 @@ describe Chef::Cookbook::Metadata do it "should deserialize to a Chef::Cookbook::Metadata object" do - deserialized_metadata.should be_a_kind_of(Chef::Cookbook::Metadata) + expect(deserialized_metadata).to be_a_kind_of(Chef::Cookbook::Metadata) end %w{ @@ -721,7 +721,7 @@ describe Chef::Cookbook::Metadata do issues_url }.each do |t| it "should match '#{t}'" do - deserialized_metadata.send(t.to_sym).should == metadata.send(t.to_sym) + expect(deserialized_metadata.send(t.to_sym)).to eq(metadata.send(t.to_sym)) end end end @@ -739,31 +739,31 @@ describe Chef::Cookbook::Metadata do it "should transform deprecated greater than syntax for :#{to_check.to_s}" do @hash[to_check.to_s]["foo::bar"] = ">> 0.2" deserial = Chef::Cookbook::Metadata.from_hash(@hash) - deserial.send(to_check)["foo::bar"].should == '> 0.2' + expect(deserial.send(to_check)["foo::bar"]).to eq('> 0.2') end it "should transform deprecated less than syntax for :#{to_check.to_s}" do @hash[to_check.to_s]["foo::bar"] = "<< 0.2" deserial = Chef::Cookbook::Metadata.from_hash(@hash) - deserial.send(to_check)["foo::bar"].should == '< 0.2' + expect(deserial.send(to_check)["foo::bar"]).to eq('< 0.2') end it "should ignore multiple dependency constraints for :#{to_check.to_s}" do @hash[to_check.to_s]["foo::bar"] = [ ">= 1.0", "<= 5.2" ] deserial = Chef::Cookbook::Metadata.from_hash(@hash) - deserial.send(to_check)["foo::bar"].should == [] + expect(deserial.send(to_check)["foo::bar"]).to eq([]) end it "should accept an empty array of dependency constraints for :#{to_check.to_s}" do @hash[to_check.to_s]["foo::bar"] = [] deserial = Chef::Cookbook::Metadata.from_hash(@hash) - deserial.send(to_check)["foo::bar"].should == [] + expect(deserial.send(to_check)["foo::bar"]).to eq([]) end it "should accept single-element arrays of dependency constraints for :#{to_check.to_s}" do @hash[to_check.to_s]["foo::bar"] = [ ">= 2.0" ] deserial = Chef::Cookbook::Metadata.from_hash(@hash) - deserial.send(to_check)["foo::bar"].should == ">= 2.0" + expect(deserial.send(to_check)["foo::bar"]).to eq(">= 2.0") end end end diff --git a/spec/unit/cookbook/syntax_check_spec.rb b/spec/unit/cookbook/syntax_check_spec.rb index 4d22e0e920..67d31cdca5 100644 --- a/spec/unit/cookbook/syntax_check_spec.rb +++ b/spec/unit/cookbook/syntax_check_spec.rb @@ -21,7 +21,7 @@ require "chef/cookbook/syntax_check" describe Chef::Cookbook::SyntaxCheck do before do - Chef::Platform.stub(:windows?) { false } + allow(Chef::Platform).to receive(:windows?) { false } end let(:cookbook_path) { File.join(CHEF_SPEC_DATA, 'cookbooks', 'openldap') } @@ -64,14 +64,14 @@ describe Chef::Cookbook::SyntaxCheck do it "creates a syntax checker given the cookbook name when Chef::Config.cookbook_path is set" do Chef::Config[:cookbook_path] = File.dirname(cookbook_path) syntax_check = Chef::Cookbook::SyntaxCheck.for_cookbook(:openldap) - syntax_check.cookbook_path.should == cookbook_path - syntax_check.ruby_files.sort.should == open_ldap_cookbook_files.sort + expect(syntax_check.cookbook_path).to eq(cookbook_path) + expect(syntax_check.ruby_files.sort).to eq(open_ldap_cookbook_files.sort) end it "creates a syntax checker given the cookbook name and cookbook_path" do syntax_check = Chef::Cookbook::SyntaxCheck.for_cookbook(:openldap, File.join(CHEF_SPEC_DATA, 'cookbooks')) - syntax_check.cookbook_path.should == cookbook_path - syntax_check.ruby_files.sort.should == open_ldap_cookbook_files.sort + expect(syntax_check.cookbook_path).to eq(cookbook_path) + expect(syntax_check.ruby_files.sort).to eq(open_ldap_cookbook_files.sort) end context "when using a standalone cookbook" do @@ -79,22 +79,22 @@ describe Chef::Cookbook::SyntaxCheck do it "creates a syntax checker given the cookbook name and cookbook_path for a standalone cookbook" do syntax_check = Chef::Cookbook::SyntaxCheck.for_cookbook(:standalone_cookbook, CHEF_SPEC_DATA) - syntax_check.cookbook_path.should == cookbook_path - syntax_check.ruby_files.should == [File.join(cookbook_path, 'recipes/default.rb')] + expect(syntax_check.cookbook_path).to eq(cookbook_path) + expect(syntax_check.ruby_files).to eq([File.join(cookbook_path, 'recipes/default.rb')]) end end describe "when first created" do it "has the path to the cookbook to syntax check" do - syntax_check.cookbook_path.should == cookbook_path + expect(syntax_check.cookbook_path).to eq(cookbook_path) end it "lists the ruby files in the cookbook" do - syntax_check.ruby_files.sort.should == @ruby_files.sort + expect(syntax_check.ruby_files.sort).to eq(@ruby_files.sort) end it "lists the erb templates in the cookbook" do - syntax_check.template_files.sort.should == @template_files.sort + expect(syntax_check.template_files.sort).to eq(@template_files.sort) end end @@ -112,33 +112,33 @@ describe Chef::Cookbook::SyntaxCheck do describe "and the files have not been syntax checked previously" do it "shows that all ruby files require a syntax check" do - syntax_check.untested_ruby_files.sort.should == @ruby_files.sort + expect(syntax_check.untested_ruby_files.sort).to eq(@ruby_files.sort) end it "shows that all template files require a syntax check" do - syntax_check.untested_template_files.sort.should == @template_files.sort + expect(syntax_check.untested_template_files.sort).to eq(@template_files.sort) end it "removes a ruby file from the list of untested files after it is marked as validated" do recipe = File.join(cookbook_path, 'recipes', 'default.rb') syntax_check.validated(recipe) - syntax_check.untested_ruby_files.should_not include(recipe) + expect(syntax_check.untested_ruby_files).not_to include(recipe) end it "removes a template file from the list of untested files after it is marked as validated" do template = File.join(cookbook_path, 'templates', 'default', 'test.erb') syntax_check.validated(template) - syntax_check.untested_template_files.should_not include(template) + expect(syntax_check.untested_template_files).not_to include(template) end it "validates all ruby files" do - syntax_check.validate_ruby_files.should be_true - syntax_check.untested_ruby_files.should be_empty + expect(syntax_check.validate_ruby_files).to be_truthy + expect(syntax_check.untested_ruby_files).to be_empty end it "validates all templates" do - syntax_check.validate_templates.should be_true - syntax_check.untested_template_files.should be_empty + expect(syntax_check.validate_templates).to be_truthy + expect(syntax_check.untested_template_files).to be_empty end describe "and a file has a syntax error" do @@ -148,22 +148,22 @@ describe Chef::Cookbook::SyntaxCheck do end it "it indicates that a ruby file has a syntax error" do - syntax_check.validate_ruby_files.should be_false + expect(syntax_check.validate_ruby_files).to be_falsey end it "does not remove the invalid file from the list of untested files" do - syntax_check.untested_ruby_files.should include(File.join(cookbook_path, 'recipes', 'default.rb')) + expect(syntax_check.untested_ruby_files).to include(File.join(cookbook_path, 'recipes', 'default.rb')) syntax_check.validate_ruby_files - syntax_check.untested_ruby_files.should include(File.join(cookbook_path, 'recipes', 'default.rb')) + expect(syntax_check.untested_ruby_files).to include(File.join(cookbook_path, 'recipes', 'default.rb')) end it "indicates that a template file has a syntax error" do - syntax_check.validate_templates.should be_false + expect(syntax_check.validate_templates).to be_falsey end it "does not remove the invalid template from the list of untested templates" do - syntax_check.untested_template_files.should include(File.join(cookbook_path, 'templates', 'default', 'borken.erb')) - lambda {syntax_check.validate_templates}.should_not change(syntax_check, :untested_template_files) + expect(syntax_check.untested_template_files).to include(File.join(cookbook_path, 'templates', 'default', 'borken.erb')) + expect {syntax_check.validate_templates}.not_to change(syntax_check, :untested_template_files) end end @@ -177,12 +177,12 @@ describe Chef::Cookbook::SyntaxCheck do end it "shows that ignored ruby files do not require a syntax check" do - syntax_check.untested_ruby_files.sort.should == @ruby_files.sort + expect(syntax_check.untested_ruby_files.sort).to eq(@ruby_files.sort) end it "does not indicate that a ruby file has a syntax error" do - syntax_check.validate_ruby_files.should be_true - syntax_check.untested_ruby_files.should be_empty + expect(syntax_check.validate_ruby_files).to be_truthy + expect(syntax_check.untested_ruby_files).to be_empty end end @@ -196,13 +196,13 @@ describe Chef::Cookbook::SyntaxCheck do end it "does not syntax check ruby files" do - syntax_check.should_not_receive(:shell_out) - syntax_check.validate_ruby_files.should be_true + expect(syntax_check).not_to receive(:shell_out) + expect(syntax_check.validate_ruby_files).to be_truthy end it "does not syntax check templates" do - syntax_check.should_not_receive(:shell_out) - syntax_check.validate_templates.should be_true + expect(syntax_check).not_to receive(:shell_out) + expect(syntax_check.validate_templates).to be_truthy end end end diff --git a/spec/unit/cookbook_loader_spec.rb b/spec/unit/cookbook_loader_spec.rb index deaf393d7a..51532778e4 100644 --- a/spec/unit/cookbook_loader_spec.rb +++ b/spec/unit/cookbook_loader_spec.rb @@ -20,7 +20,7 @@ require 'spec_helper' describe Chef::CookbookLoader do before do - Chef::Platform.stub(:windows?) {false} + allow(Chef::Platform).to receive(:windows?) {false} end let(:repo_paths) do [ @@ -40,7 +40,7 @@ describe Chef::CookbookLoader do cookbook_paths.delete_if { |path| File.basename(path) == "chefignore" } cookbook_paths.each do |cookbook_path| - Chef::Cookbook::CookbookVersionLoader.should_receive(:new). + expect(Chef::Cookbook::CookbookVersionLoader).to receive(:new). with(cookbook_path, anything). once. and_call_original @@ -56,19 +56,19 @@ describe Chef::CookbookLoader do describe "[]" do it "should return cookbook objects with []" do - cookbook_loader[:openldap].should be_a_kind_of(Chef::CookbookVersion) + expect(cookbook_loader[:openldap]).to be_a_kind_of(Chef::CookbookVersion) end it "should raise an exception if it cannot find a cookbook with []" do - lambda { cookbook_loader[:monkeypoop] }.should raise_error(Chef::Exceptions::CookbookNotFoundInRepo) + expect { cookbook_loader[:monkeypoop] }.to raise_error(Chef::Exceptions::CookbookNotFoundInRepo) end it "should allow you to look up available cookbooks with [] and a symbol" do - cookbook_loader[:openldap].name.should eql(:openldap) + expect(cookbook_loader[:openldap].name).to eql(:openldap) end it "should allow you to look up available cookbooks with [] and a string" do - cookbook_loader["openldap"].name.should eql(:openldap) + expect(cookbook_loader["openldap"].name).to eql(:openldap) end end @@ -78,8 +78,8 @@ describe Chef::CookbookLoader do cookbook_loader.each do |cookbook_name, cookbook| seen[cookbook_name] = true end - seen.should have_key("openldap") - seen.should have_key("apache2") + expect(seen).to have_key("openldap") + expect(seen).to have_key("apache2") end it "should iterate in alphabetical order" do @@ -87,86 +87,86 @@ describe Chef::CookbookLoader do cookbook_loader.each do |cookbook_name, cookbook| seen << cookbook_name end - seen[0].should == "angrybash" - seen[1].should == "apache2" - seen[2].should == "borken" - seen[3].should == "ignorken" - seen[4].should == "java" - seen[5].should == "name-mismatch" - seen[6].should == "openldap" + expect(seen[0]).to eq("angrybash") + expect(seen[1]).to eq("apache2") + expect(seen[2]).to eq("borken") + expect(seen[3]).to eq("ignorken") + expect(seen[4]).to eq("java") + expect(seen[5]).to eq("name-mismatch") + expect(seen[6]).to eq("openldap") end end describe "referencing cookbook files" do it "should find all the cookbooks in the cookbook path" do cookbook_loader.load_cookbooks - cookbook_loader.should have_key(:openldap) - cookbook_loader.should have_key(:apache2) + expect(cookbook_loader).to have_key(:openldap) + expect(cookbook_loader).to have_key(:apache2) end it "should allow you to override an attribute file via cookbook_path" do - cookbook_loader[:openldap].attribute_filenames.detect { |f| + expect(cookbook_loader[:openldap].attribute_filenames.detect { |f| f =~ /cookbooks\/openldap\/attributes\/default.rb/ - }.should_not eql(nil) - cookbook_loader[:openldap].attribute_filenames.detect { |f| + }).not_to eql(nil) + expect(cookbook_loader[:openldap].attribute_filenames.detect { |f| f =~ /kitchen\/openldap\/attributes\/default.rb/ - }.should eql(nil) + }).to eql(nil) end it "should load different attribute files from deeper paths" do - cookbook_loader[:openldap].attribute_filenames.detect { |f| + expect(cookbook_loader[:openldap].attribute_filenames.detect { |f| f =~ /kitchen\/openldap\/attributes\/robinson.rb/ - }.should_not eql(nil) + }).not_to eql(nil) end it "should allow you to override a definition file via cookbook_path" do - cookbook_loader[:openldap].definition_filenames.detect { |f| + expect(cookbook_loader[:openldap].definition_filenames.detect { |f| f =~ /cookbooks\/openldap\/definitions\/client.rb/ - }.should_not eql(nil) - cookbook_loader[:openldap].definition_filenames.detect { |f| + }).not_to eql(nil) + expect(cookbook_loader[:openldap].definition_filenames.detect { |f| f =~ /kitchen\/openldap\/definitions\/client.rb/ - }.should eql(nil) + }).to eql(nil) end it "should load definition files from deeper paths" do - cookbook_loader[:openldap].definition_filenames.detect { |f| + expect(cookbook_loader[:openldap].definition_filenames.detect { |f| f =~ /kitchen\/openldap\/definitions\/drewbarrymore.rb/ - }.should_not eql(nil) + }).not_to eql(nil) end it "should allow you to override a recipe file via cookbook_path" do - cookbook_loader[:openldap].recipe_filenames.detect { |f| + expect(cookbook_loader[:openldap].recipe_filenames.detect { |f| f =~ /cookbooks\/openldap\/recipes\/gigantor.rb/ - }.should_not eql(nil) - cookbook_loader[:openldap].recipe_filenames.detect { |f| + }).not_to eql(nil) + expect(cookbook_loader[:openldap].recipe_filenames.detect { |f| f =~ /kitchen\/openldap\/recipes\/gigantor.rb/ - }.should eql(nil) + }).to eql(nil) end it "should load recipe files from deeper paths" do - cookbook_loader[:openldap].recipe_filenames.detect { |f| + expect(cookbook_loader[:openldap].recipe_filenames.detect { |f| f =~ /kitchen\/openldap\/recipes\/woot.rb/ - }.should_not eql(nil) + }).not_to eql(nil) end it "should allow you to have an 'ignore' file, which skips loading files in later cookbooks" do - cookbook_loader[:openldap].recipe_filenames.detect { |f| + expect(cookbook_loader[:openldap].recipe_filenames.detect { |f| f =~ /kitchen\/openldap\/recipes\/ignoreme.rb/ - }.should eql(nil) + }).to eql(nil) end it "should find files that start with a ." do - cookbook_loader[:openldap].file_filenames.detect { |f| + expect(cookbook_loader[:openldap].file_filenames.detect { |f| f =~ /\.dotfile$/ - }.should =~ /\.dotfile$/ - cookbook_loader[:openldap].file_filenames.detect { |f| + }).to match(/\.dotfile$/) + expect(cookbook_loader[:openldap].file_filenames.detect { |f| f =~ /\.ssh\/id_rsa$/ - }.should =~ /\.ssh\/id_rsa$/ + }).to match(/\.ssh\/id_rsa$/) end it "should load the metadata for the cookbook" do - cookbook_loader.metadata[:openldap].name.to_s.should == "openldap" - cookbook_loader.metadata[:openldap].should be_a_kind_of(Chef::Cookbook::Metadata) + expect(cookbook_loader.metadata[:openldap].name.to_s).to eq("openldap") + expect(cookbook_loader.metadata[:openldap]).to be_a_kind_of(Chef::Cookbook::Metadata) end end # referencing cookbook files @@ -199,27 +199,27 @@ describe Chef::CookbookLoader do cookbook_loader.each do |cookbook_name, cookbook| seen[cookbook_name] = true end - seen.should have_key("openldap") + expect(seen).to have_key("openldap") end it "should not duplicate keys when serialized to JSON" do # Chef JSON serialization will generate duplicate keys if given # a Hash containing matching string and symbol keys. See CHEF-4571. aa = cookbook_loader["openldap"] - aa.to_hash["metadata"].recipes.keys.should_not include(:openldap) - aa.to_hash["metadata"].recipes.keys.should include("openldap") + expect(aa.to_hash["metadata"].recipes.keys).not_to include(:openldap) + expect(aa.to_hash["metadata"].recipes.keys).to include("openldap") expected_desc = "Main Open LDAP configuration" - aa.to_hash["metadata"].recipes["openldap"].should == expected_desc + expect(aa.to_hash["metadata"].recipes["openldap"]).to eq(expected_desc) raw = Chef::JSONCompat.to_json(aa.to_hash["metadata"].recipes) search_str = "\"openldap\":\"" key_idx = raw.index(search_str) - key_idx.should be > 0 + expect(key_idx).to be > 0 dup_idx = raw[(key_idx + 1)..-1].index(search_str) - dup_idx.should be_nil + expect(dup_idx).to be_nil end it "should not load the cookbook again when accessed" do - cookbook_loader.should_not_receive('load_cookbook') + expect(cookbook_loader).not_to receive('load_cookbook') cookbook_loader["openldap"] end @@ -228,11 +228,11 @@ describe Chef::CookbookLoader do cookbook_loader.each do |cookbook_name, cookbook| seen[cookbook_name] = true end - seen.should_not have_key("apache2") + expect(seen).not_to have_key("apache2") end it "should load another cookbook lazily with []" do - cookbook_loader["apache2"].should be_a_kind_of(Chef::CookbookVersion) + expect(cookbook_loader["apache2"]).to be_a_kind_of(Chef::CookbookVersion) end context "when an unrelated cookbook has invalid metadata" do @@ -265,8 +265,8 @@ describe Chef::CookbookLoader do cookbook_loader.each do |cookbook_name, cookbook| seen[cookbook_name] = true end - seen.should have_key("openldap") - seen.should have_key("apache2") + expect(seen).to have_key("openldap") + expect(seen).to have_key("apache2") end end end # loading only one cookbook @@ -279,8 +279,8 @@ describe Chef::CookbookLoader do it "loads the correct cookbook" do cookbook_version = cookbook_loader["name-mismatch"] - cookbook_version.should be_a_kind_of(Chef::CookbookVersion) - cookbook_version.name.should == :"name-mismatch" + expect(cookbook_version).to be_a_kind_of(Chef::CookbookVersion) + expect(cookbook_version.name).to eq(:"name-mismatch") end end diff --git a/spec/unit/cookbook_manifest_spec.rb b/spec/unit/cookbook_manifest_spec.rb index e87b8e1e9a..8b50b040c2 100644 --- a/spec/unit/cookbook_manifest_spec.rb +++ b/spec/unit/cookbook_manifest_spec.rb @@ -210,8 +210,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "examplehost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "afile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum-host" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum-host") end it "should return a manifest record based on priority preference: platform & full version" do @@ -221,8 +221,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "afile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum-platver-full" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum-platver-full") end it "should return a manifest record based on priority preference: platform & partial version" do @@ -232,8 +232,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "afile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum-platver-partial" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum-platver-partial") end it "should return a manifest record based on priority preference: platform only" do @@ -243,8 +243,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "afile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum-plat" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum-plat") end it "should return a manifest record based on priority preference: default" do @@ -254,8 +254,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "afile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum-default" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum-default") end it "should return a manifest record based on priority preference: platform & full version - platform_version variant 1" do @@ -265,8 +265,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "bfile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum2-platver-full" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum2-platver-full") end it "should return a manifest record based on priority preference: platform & partial version - platform_version variant 1" do @@ -276,8 +276,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "bfile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum2-platver-partial" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum2-platver-partial") end it "should return a manifest record based on priority preference: platform & full version - platform_version variant 2" do @@ -287,8 +287,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "bfile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum3-platver-full" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum3-platver-full") end it "should return a manifest record based on priority preference: platform & full version - platform_version variant 3" do @@ -298,8 +298,8 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_record = @cookbook.preferred_manifest_record(node, :files, "bfile.rb") - manifest_record.should_not be_nil - manifest_record[:checksum].should == "csum4-platver-full" + expect(manifest_record).not_to be_nil + expect(manifest_record[:checksum]).to eq("csum4-platver-full") end describe "when fetching the contents of a directory by file specificity" do @@ -311,11 +311,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "examplehost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum-host-1", "csum-host-2"] + expect(checksums.sort).to eq(["csum-host-1", "csum-host-2"]) end it "should return a directory of manifest records based on priority preference: platform & full version" do @@ -325,11 +325,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum-platver-full-1", "csum-platver-full-2"] + expect(checksums.sort).to eq(["csum-platver-full-1", "csum-platver-full-2"]) end it "should return a directory of manifest records based on priority preference: platform & partial version" do @@ -339,11 +339,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum-platver-partial-1", "csum-platver-partial-2"] + expect(checksums.sort).to eq(["csum-platver-partial-1", "csum-platver-partial-2"]) end it "should return a directory of manifest records based on priority preference: platform only" do @@ -353,11 +353,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum-plat-1", "csum-plat-2"] + expect(checksums.sort).to eq(["csum-plat-1", "csum-plat-2"]) end it "should return a directory of manifest records based on priority preference: default" do @@ -367,11 +367,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum-default-1", "csum-default-2"] + expect(checksums.sort).to eq(["csum-default-1", "csum-default-2"]) end it "should return a manifest record based on priority preference: platform & full version - platform_version variant 1" do @@ -381,11 +381,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum2-platver-full-1", "csum2-platver-full-2"] + expect(checksums.sort).to eq(["csum2-platver-full-1", "csum2-platver-full-2"]) end it "should return a manifest record based on priority preference: platform & partial version - platform_version variant 1" do @@ -395,11 +395,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum2-platver-partial-1", "csum2-platver-partial-2"] + expect(checksums.sort).to eq(["csum2-platver-partial-1", "csum2-platver-partial-2"]) end it "should return a manifest record based on priority preference: platform & full version - platform_version variant 2" do @@ -409,11 +409,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum3-platver-full-1", "csum3-platver-full-2"] + expect(checksums.sort).to eq(["csum3-platver-full-1", "csum3-platver-full-2"]) end it "should return a manifest record based on priority preference: platform & full version - platform_version variant 3" do @@ -423,11 +423,11 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" manifest_records = @cookbook.preferred_manifest_records_for_directory(node, :files, "adirectory") - manifest_records.should_not be_nil - manifest_records.size.should == 2 + expect(manifest_records).not_to be_nil + expect(manifest_records.size).to eq(2) checksums = manifest_records.map{ |manifest_record| manifest_record[:checksum] } - checksums.sort.should == ["csum4-platver-full-1", "csum4-platver-full-2"] + expect(checksums.sort).to eq(["csum4-platver-full-1", "csum4-platver-full-2"]) end end @@ -441,10 +441,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "examplehost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.host', 'anotherfile2.rb.host'] + expect(filenames.sort).to eq(['anotherfile1.rb.host', 'anotherfile2.rb.host']) end it "should return a list of relative paths based on priority preference: platform & full version" do @@ -454,10 +454,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version'] + expect(filenames.sort).to eq(['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version']) end it "should return a list of relative paths based on priority preference: platform & partial version" do @@ -467,10 +467,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.platform-partial-version', 'anotherfile2.rb.platform-partial-version'] + expect(filenames.sort).to eq(['anotherfile1.rb.platform-partial-version', 'anotherfile2.rb.platform-partial-version']) end it "should return a list of relative paths based on priority preference: platform only" do @@ -480,10 +480,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.platform', 'anotherfile2.rb.platform'] + expect(filenames.sort).to eq(['anotherfile1.rb.platform', 'anotherfile2.rb.platform']) end it "should return a list of relative paths based on priority preference: default" do @@ -493,10 +493,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.default', 'anotherfile2.rb.default'] + expect(filenames.sort).to eq(['anotherfile1.rb.default', 'anotherfile2.rb.default']) end it "should return a list of relative paths based on priority preference: platform & full version - platform_version variant 1" do @@ -506,10 +506,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version'] + expect(filenames.sort).to eq(['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version']) end it "should return a list of relative paths based on priority preference: platform & partial version - platform_version variant 1" do @@ -519,10 +519,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.platform-partial-version', 'anotherfile2.rb.platform-partial-version'] + expect(filenames.sort).to eq(['anotherfile1.rb.platform-partial-version', 'anotherfile2.rb.platform-partial-version']) end it "should return a list of relative paths based on priority preference: platform & full version - platform_version variant 2" do @@ -532,10 +532,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version'] + expect(filenames.sort).to eq(['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version']) end it "should return a list of relative paths based on priority preference: platform & full version - platform_version variant 3" do @@ -545,10 +545,10 @@ describe "Chef::CookbookVersion manifest" do node.automatic_attrs[:fqdn] = "differenthost.example.org" filenames = @cookbook.relative_filenames_in_preferred_directory(node, :files, "adirectory") - filenames.should_not be_nil - filenames.size.should == 2 + expect(filenames).not_to be_nil + expect(filenames.size).to eq(2) - filenames.sort.should == ['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version'] + expect(filenames.sort).to eq(['anotherfile1.rb.platform-full-version', 'anotherfile2.rb.platform-full-version']) end end end diff --git a/spec/unit/cookbook_site_streaming_uploader_spec.rb b/spec/unit/cookbook_site_streaming_uploader_spec.rb index 1d7009e31c..ef0f649163 100644 --- a/spec/unit/cookbook_site_streaming_uploader_spec.rb +++ b/spec/unit/cookbook_site_streaming_uploader_spec.rb @@ -42,16 +42,16 @@ describe Chef::CookbookSiteStreamingUploader do @cookbook_repo = File.expand_path(File.join(CHEF_SPEC_DATA, 'cookbooks')) @loader = Chef::CookbookLoader.new(@cookbook_repo) @loader.load_cookbooks - File.stub(:unlink).and_return() + allow(File).to receive(:unlink) end it "should create the cookbook tmp dir" do cookbook = @loader[:openldap] files_count = Dir.glob(File.join(@cookbook_repo, cookbook.name.to_s, '**', '*'), File::FNM_DOTMATCH).count { |file| File.file?(file) } - Tempfile.should_receive(:new).with("chef-#{cookbook.name}-build").and_return(FakeTempfile.new("chef-#{cookbook.name}-build")) - FileUtils.should_receive(:mkdir_p).exactly(files_count + 1).times - FileUtils.should_receive(:cp).exactly(files_count).times + expect(Tempfile).to receive(:new).with("chef-#{cookbook.name}-build").and_return(FakeTempfile.new("chef-#{cookbook.name}-build")) + expect(FileUtils).to receive(:mkdir_p).exactly(files_count + 1).times + expect(FileUtils).to receive(:cp).exactly(files_count).times Chef::CookbookSiteStreamingUploader.create_build_dir(cookbook) end @@ -64,39 +64,39 @@ describe Chef::CookbookSiteStreamingUploader do @secret_filename = File.join(CHEF_SPEC_DATA, 'ssl/private_key.pem') @rsa_key = File.read(@secret_filename) response = Net::HTTPResponse.new('1.0', '200', 'OK') - Net::HTTP.any_instance.stub(:request).and_return(response) + allow_any_instance_of(Net::HTTP).to receive(:request).and_return(response) end it "should send an http request" do - Net::HTTP.any_instance.should_receive(:request) + expect_any_instance_of(Net::HTTP).to receive(:request) Chef::CookbookSiteStreamingUploader.make_request(:post, @uri, 'bill', @secret_filename) end it "should read the private key file" do - File.should_receive(:read).with(@secret_filename).and_return(@rsa_key) + expect(File).to receive(:read).with(@secret_filename).and_return(@rsa_key) Chef::CookbookSiteStreamingUploader.make_request(:post, @uri, 'bill', @secret_filename) end it "should add the authentication signed header" do - Mixlib::Authentication::SigningObject.any_instance.should_receive(:sign).and_return({}) + expect_any_instance_of(Mixlib::Authentication::SigningObject).to receive(:sign).and_return({}) Chef::CookbookSiteStreamingUploader.make_request(:post, @uri, 'bill', @secret_filename) end it "should be able to send post requests" do post = Net::HTTP::Post.new(@uri, {}) - Net::HTTP::Post.should_receive(:new).once.and_return(post) - Net::HTTP::Put.should_not_receive(:new) - Net::HTTP::Get.should_not_receive(:new) + expect(Net::HTTP::Post).to receive(:new).once.and_return(post) + expect(Net::HTTP::Put).not_to receive(:new) + expect(Net::HTTP::Get).not_to receive(:new) Chef::CookbookSiteStreamingUploader.make_request(:post, @uri, 'bill', @secret_filename) end it "should be able to send put requests" do put = Net::HTTP::Put.new(@uri, {}) - Net::HTTP::Post.should_not_receive(:new) - Net::HTTP::Put.should_receive(:new).once.and_return(put) - Net::HTTP::Get.should_not_receive(:new) + expect(Net::HTTP::Post).not_to receive(:new) + expect(Net::HTTP::Put).to receive(:new).once.and_return(put) + expect(Net::HTTP::Get).not_to receive(:new) Chef::CookbookSiteStreamingUploader.make_request(:put, @uri, 'bill', @secret_filename) end @@ -126,19 +126,19 @@ describe Chef::CookbookSiteStreamingUploader do @uri = "https://cookbooks.dummy.com/api/v1/cookbooks" uri_info = URI.parse(@uri) @http = Net::HTTP.new(uri_info.host, uri_info.port) - Net::HTTP.should_receive(:new).with(uri_info.host, uri_info.port).and_return(@http) + expect(Net::HTTP).to receive(:new).with(uri_info.host, uri_info.port).and_return(@http) end it "should be VERIFY_NONE when ssl_verify_mode is :verify_none" do Chef::Config[:ssl_verify_mode] = :verify_none Chef::CookbookSiteStreamingUploader.make_request(:post, @uri, 'bill', @secret_filename) - @http.verify_mode.should == OpenSSL::SSL::VERIFY_NONE + expect(@http.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) end it "should be VERIFY_PEER when ssl_verify_mode is :verify_peer" do Chef::Config[:ssl_verify_mode] = :verify_peer Chef::CookbookSiteStreamingUploader.make_request(:post, @uri, 'bill', @secret_filename) - @http.verify_mode.should == OpenSSL::SSL::VERIFY_PEER + expect(@http.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) end end @@ -151,17 +151,17 @@ describe Chef::CookbookSiteStreamingUploader do end it "should create a StreamPart" do - @stream_part.should be_instance_of(Chef::CookbookSiteStreamingUploader::StreamPart) + expect(@stream_part).to be_instance_of(Chef::CookbookSiteStreamingUploader::StreamPart) end it "should expose its size" do - @stream_part.size.should eql(File.size(@file)) + expect(@stream_part.size).to eql(File.size(@file)) end it "should read with offset and how_much" do content = @file.read(4) @file.rewind - @stream_part.read(0, 4).should eql(content) + expect(@stream_part.read(0, 4)).to eql(content) end end # StreamPart @@ -173,15 +173,15 @@ describe Chef::CookbookSiteStreamingUploader do end it "should create a StringPart" do - @string_part.should be_instance_of(Chef::CookbookSiteStreamingUploader::StringPart) + expect(@string_part).to be_instance_of(Chef::CookbookSiteStreamingUploader::StringPart) end it "should expose its size" do - @string_part.size.should eql(@str.size) + expect(@string_part.size).to eql(@str.size) end it "should read with offset and how_much" do - @string_part.read(2, 4).should eql(@str[2, 4]) + expect(@string_part.read(2, 4)).to eql(@str[2, 4]) end end # StringPart @@ -198,21 +198,21 @@ describe Chef::CookbookSiteStreamingUploader do end it "should create a MultipartStream" do - @multipart_stream.should be_instance_of(Chef::CookbookSiteStreamingUploader::MultipartStream) + expect(@multipart_stream).to be_instance_of(Chef::CookbookSiteStreamingUploader::MultipartStream) end it "should expose its size" do - @multipart_stream.size.should eql(@stream1.size + @stream2.size) + expect(@multipart_stream.size).to eql(@stream1.size + @stream2.size) end it "should read with how_much" do - @multipart_stream.read(10).should eql("#{@string1}#{@string2}"[0, 10]) + expect(@multipart_stream.read(10)).to eql("#{@string1}#{@string2}"[0, 10]) end it "should read receiving destination buffer as second argument (CHEF-4456: Ruby 2 compat)" do dst_buf = '' @multipart_stream.read(10, dst_buf) - dst_buf.should eql("#{@string1}#{@string2}"[0, 10]) + expect(dst_buf).to eql("#{@string1}#{@string2}"[0, 10]) end end # MultipartStream diff --git a/spec/unit/cookbook_spec.rb b/spec/unit/cookbook_spec.rb index 9bcea97d98..7b3cda2af1 100644 --- a/spec/unit/cookbook_spec.rb +++ b/spec/unit/cookbook_spec.rb @@ -33,43 +33,43 @@ describe Chef::CookbookVersion do end it "should have a name" do - @cookbook.name.should == :openldap + expect(@cookbook.name).to eq(:openldap) end it "should allow you to set the list of attribute files and create the mapping from short names to paths" do @cookbook.attribute_filenames = [ "attributes/one.rb", "attributes/two.rb" ] - @cookbook.attribute_filenames.should == [ "attributes/one.rb", "attributes/two.rb" ] - @cookbook.attribute_filenames_by_short_filename.keys.sort.should eql(["one", "two"]) - @cookbook.attribute_filenames_by_short_filename["one"].should == "attributes/one.rb" - @cookbook.attribute_filenames_by_short_filename["two"].should == "attributes/two.rb" + expect(@cookbook.attribute_filenames).to eq([ "attributes/one.rb", "attributes/two.rb" ]) + expect(@cookbook.attribute_filenames_by_short_filename.keys.sort).to eql(["one", "two"]) + expect(@cookbook.attribute_filenames_by_short_filename["one"]).to eq("attributes/one.rb") + expect(@cookbook.attribute_filenames_by_short_filename["two"]).to eq("attributes/two.rb") end it "should allow you to set the list of recipe files and create the mapping of recipe short name to filename" do @cookbook.recipe_filenames = [ "recipes/one.rb", "recipes/two.rb" ] - @cookbook.recipe_filenames.should == [ "recipes/one.rb", "recipes/two.rb" ] - @cookbook.recipe_filenames_by_name.keys.sort.should eql(["one", "two"]) - @cookbook.recipe_filenames_by_name["one"].should == "recipes/one.rb" - @cookbook.recipe_filenames_by_name["two"].should == "recipes/two.rb" + expect(@cookbook.recipe_filenames).to eq([ "recipes/one.rb", "recipes/two.rb" ]) + expect(@cookbook.recipe_filenames_by_name.keys.sort).to eql(["one", "two"]) + expect(@cookbook.recipe_filenames_by_name["one"]).to eq("recipes/one.rb") + expect(@cookbook.recipe_filenames_by_name["two"]).to eq("recipes/two.rb") end it "should generate a list of recipes by fully-qualified name" do @cookbook.recipe_filenames = [ "recipes/one.rb", "/recipes/two.rb", "three.rb" ] - @cookbook.fully_qualified_recipe_names.include?("openldap::one").should == true - @cookbook.fully_qualified_recipe_names.include?("openldap::two").should == true - @cookbook.fully_qualified_recipe_names.include?("openldap::three").should == true + expect(@cookbook.fully_qualified_recipe_names.include?("openldap::one")).to eq(true) + expect(@cookbook.fully_qualified_recipe_names.include?("openldap::two")).to eq(true) + expect(@cookbook.fully_qualified_recipe_names.include?("openldap::three")).to eq(true) end it "should find a preferred file" do - pending + skip end it "should not return an unchanged preferred file" do pending - @cookbook.preferred_filename(@node, :files, 'a-filename', 'the-checksum').should be_nil + expect(@cookbook.preferred_filename(@node, :files, 'a-filename', 'the-checksum')).to be_nil end it "should raise an ArgumentException if you try to load a bad recipe name" do - lambda { @cookbook.load_recipe("doesnt_exist", @node) }.should raise_error(ArgumentError) + expect { @cookbook.load_recipe("doesnt_exist", @node) }.to raise_error(ArgumentError) end end diff --git a/spec/unit/cookbook_version_spec.rb b/spec/unit/cookbook_version_spec.rb index 8436e5c480..3d0348553b 100644 --- a/spec/unit/cookbook_version_spec.rb +++ b/spec/unit/cookbook_version_spec.rb @@ -24,58 +24,58 @@ describe Chef::CookbookVersion do end it "has a name" do - @cookbook_version.name.should == 'tatft' + expect(@cookbook_version.name).to eq('tatft') end it "has no attribute files" do - @cookbook_version.attribute_filenames.should be_empty + expect(@cookbook_version.attribute_filenames).to be_empty end it "has no resource definition files" do - @cookbook_version.definition_filenames.should be_empty + expect(@cookbook_version.definition_filenames).to be_empty end it "has no cookbook files" do - @cookbook_version.file_filenames.should be_empty + expect(@cookbook_version.file_filenames).to be_empty end it "has no recipe files" do - @cookbook_version.recipe_filenames.should be_empty + expect(@cookbook_version.recipe_filenames).to be_empty end it "has no library files" do - @cookbook_version.library_filenames.should be_empty + expect(@cookbook_version.library_filenames).to be_empty end it "has no LWRP resource files" do - @cookbook_version.resource_filenames.should be_empty + expect(@cookbook_version.resource_filenames).to be_empty end it "has no LWRP provider files" do - @cookbook_version.provider_filenames.should be_empty + expect(@cookbook_version.provider_filenames).to be_empty end it "has no metadata files" do - @cookbook_version.metadata_filenames.should be_empty + expect(@cookbook_version.metadata_filenames).to be_empty end it "is not frozen" do - @cookbook_version.should_not be_frozen_version + expect(@cookbook_version).not_to be_frozen_version end it "can be frozen" do @cookbook_version.freeze_version - @cookbook_version.should be_frozen_version + expect(@cookbook_version).to be_frozen_version end it "is \"ready\"" do # WTF is this? what are the valid states? and why aren't they set with encapsulating methods? # [Dan 15-Jul-2010] - @cookbook_version.status.should == :ready + expect(@cookbook_version.status).to eq(:ready) end it "has empty metadata" do - @cookbook_version.metadata.should == Chef::Cookbook::Metadata.new + expect(@cookbook_version.metadata).to eq(Chef::Cookbook::Metadata.new) end it "creates a manifest hash of its contents" do @@ -92,7 +92,7 @@ describe Chef::CookbookVersion do "metadata"=>Chef::Cookbook::Metadata.new, "version"=>"0.0.0", "name"=>"tatft-0.0.0"} - @cookbook_version.manifest.should == expected + expect(@cookbook_version.manifest).to eq(expected) end end @@ -144,90 +144,90 @@ describe Chef::CookbookVersion do it "generates a manifest containing the cookbook's files" do manifest = @cookbook_version.manifest - manifest["metadata"].should == Chef::Cookbook::Metadata.new - manifest["cookbook_name"].should == "tatft" + expect(manifest["metadata"]).to eq(Chef::Cookbook::Metadata.new) + expect(manifest["cookbook_name"]).to eq("tatft") - manifest["recipes"].should have(1).recipe_file + expect(manifest["recipes"].size).to eq(1) recipe = manifest["recipes"].first - recipe["name"].should == "default.rb" - recipe["path"].should == "recipes/default.rb" - recipe["checksum"].should match(MD5) - recipe["specificity"].should == "default" + expect(recipe["name"]).to eq("default.rb") + expect(recipe["path"]).to eq("recipes/default.rb") + expect(recipe["checksum"]).to match(MD5) + expect(recipe["specificity"]).to eq("default") - manifest["definitions"].should have(1).definition_file + expect(manifest["definitions"].size).to eq(1) definition = manifest["definitions"].first - definition["name"].should == "runit_service.rb" - definition["path"].should == "definitions/runit_service.rb" - definition["checksum"].should match(MD5) - definition["specificity"].should == "default" + expect(definition["name"]).to eq("runit_service.rb") + expect(definition["path"]).to eq("definitions/runit_service.rb") + expect(definition["checksum"]).to match(MD5) + expect(definition["specificity"]).to eq("default") - manifest["libraries"].should have(1).library_file + expect(manifest["libraries"].size).to eq(1) library = manifest["libraries"].first - library["name"].should == "ownage.rb" - library["path"].should == "libraries/ownage.rb" - library["checksum"].should match(MD5) - library["specificity"].should == "default" + expect(library["name"]).to eq("ownage.rb") + expect(library["path"]).to eq("libraries/ownage.rb") + expect(library["checksum"]).to match(MD5) + expect(library["specificity"]).to eq("default") - manifest["attributes"].should have(1).attribute_file + expect(manifest["attributes"].size).to eq(1) attribute_file = manifest["attributes"].first - attribute_file["name"].should == "default.rb" - attribute_file["path"].should == "attributes/default.rb" - attribute_file["checksum"].should match(MD5) - attribute_file["specificity"].should == "default" + expect(attribute_file["name"]).to eq("default.rb") + expect(attribute_file["path"]).to eq("attributes/default.rb") + expect(attribute_file["checksum"]).to match(MD5) + expect(attribute_file["specificity"]).to eq("default") - manifest["files"].should have(1).cookbook_file + expect(manifest["files"].size).to eq(1) cookbook_file = manifest["files"].first - cookbook_file["name"].should == "giant_blob.tgz" - cookbook_file["path"].should == "files/default/giant_blob.tgz" - cookbook_file["checksum"].should match(MD5) - cookbook_file["specificity"].should == "default" + expect(cookbook_file["name"]).to eq("giant_blob.tgz") + expect(cookbook_file["path"]).to eq("files/default/giant_blob.tgz") + expect(cookbook_file["checksum"]).to match(MD5) + expect(cookbook_file["specificity"]).to eq("default") - manifest["templates"].should have(1).template + expect(manifest["templates"].size).to eq(1) template = manifest["templates"].first - template["name"].should == "configuration.erb" - template["path"].should == "templates/default/configuration.erb" - template["checksum"].should match(MD5) - template["specificity"].should == "default" + expect(template["name"]).to eq("configuration.erb") + expect(template["path"]).to eq("templates/default/configuration.erb") + expect(template["checksum"]).to match(MD5) + expect(template["specificity"]).to eq("default") - manifest["resources"].should have(1).lwr + expect(manifest["resources"].size).to eq(1) lwr = manifest["resources"].first - lwr["name"].should == "lwr.rb" - lwr["path"].should == "resources/lwr.rb" - lwr["checksum"].should match(MD5) - lwr["specificity"].should == "default" + expect(lwr["name"]).to eq("lwr.rb") + expect(lwr["path"]).to eq("resources/lwr.rb") + expect(lwr["checksum"]).to match(MD5) + expect(lwr["specificity"]).to eq("default") - manifest["providers"].should have(1).lwp + expect(manifest["providers"].size).to eq(1) lwp = manifest["providers"].first - lwp["name"].should == "lwp.rb" - lwp["path"].should == "providers/lwp.rb" - lwp["checksum"].should match(MD5) - lwp["specificity"].should == "default" + expect(lwp["name"]).to eq("lwp.rb") + expect(lwp["path"]).to eq("providers/lwp.rb") + expect(lwp["checksum"]).to match(MD5) + expect(lwp["specificity"]).to eq("default") - manifest["root_files"].should have(1).file_in_the_cookbook_root + expect(manifest["root_files"].size).to eq(1) readme = manifest["root_files"].first - readme["name"].should == "README.rdoc" - readme["path"].should == "README.rdoc" - readme["checksum"].should match(MD5) - readme["specificity"].should == "default" + expect(readme["name"]).to eq("README.rdoc") + expect(readme["path"]).to eq("README.rdoc") + expect(readme["checksum"]).to match(MD5) + expect(readme["specificity"]).to eq("default") end it "determines whether a template is available for a given node" do - @cookbook_version.should have_template_for_node(@node, "configuration.erb") - @cookbook_version.should_not have_template_for_node(@node, "missing.erb") + expect(@cookbook_version).to have_template_for_node(@node, "configuration.erb") + expect(@cookbook_version).not_to have_template_for_node(@node, "missing.erb") end it "determines whether a cookbook_file is available for a given node" do - @cookbook_version.should have_cookbook_file_for_node(@node, "giant_blob.tgz") - @cookbook_version.should_not have_cookbook_file_for_node(@node, "missing.txt") + expect(@cookbook_version).to have_cookbook_file_for_node(@node, "giant_blob.tgz") + expect(@cookbook_version).not_to have_cookbook_file_for_node(@node, "missing.txt") end describe "raises an error when attempting to load a missing cookbook_file and" do @@ -243,12 +243,12 @@ describe Chef::CookbookVersion do it "describes the cookbook and version" do useful_explanation = Regexp.new(Regexp.escape("Cookbook 'tatft' (0.0.0) does not contain")) - @attempt_to_load_file.should raise_error(Chef::Exceptions::FileNotFound, useful_explanation) + expect(@attempt_to_load_file).to raise_error(Chef::Exceptions::FileNotFound, useful_explanation) end it "lists suggested places to look" do useful_explanation = Regexp.new(Regexp.escape("files/default/no-such-thing.txt")) - @attempt_to_load_file.should raise_error(Chef::Exceptions::FileNotFound, useful_explanation) + expect(@attempt_to_load_file).to raise_error(Chef::Exceptions::FileNotFound, useful_explanation) end end end @@ -273,80 +273,80 @@ describe Chef::CookbookVersion do it "generates a manifest containing the cookbook's files" do manifest = @cookbook_version.manifest - manifest["metadata"].should == Chef::Cookbook::Metadata.new - manifest["cookbook_name"].should == "blarghle" + expect(manifest["metadata"]).to eq(Chef::Cookbook::Metadata.new) + expect(manifest["cookbook_name"]).to eq("blarghle") - manifest["recipes"].should have(1).recipe_file + expect(manifest["recipes"].size).to eq(1) recipe = manifest["recipes"].first - recipe["name"].should == "default.rb" - recipe["path"].should == "recipes/default.rb" - recipe["checksum"].should match(MD5) - recipe["specificity"].should == "default" + expect(recipe["name"]).to eq("default.rb") + expect(recipe["path"]).to eq("recipes/default.rb") + expect(recipe["checksum"]).to match(MD5) + expect(recipe["specificity"]).to eq("default") - manifest["definitions"].should have(1).definition_file + expect(manifest["definitions"].size).to eq(1) definition = manifest["definitions"].first - definition["name"].should == "runit_service.rb" - definition["path"].should == "definitions/runit_service.rb" - definition["checksum"].should match(MD5) - definition["specificity"].should == "default" + expect(definition["name"]).to eq("runit_service.rb") + expect(definition["path"]).to eq("definitions/runit_service.rb") + expect(definition["checksum"]).to match(MD5) + expect(definition["specificity"]).to eq("default") - manifest["libraries"].should have(1).library_file + expect(manifest["libraries"].size).to eq(1) library = manifest["libraries"].first - library["name"].should == "ownage.rb" - library["path"].should == "libraries/ownage.rb" - library["checksum"].should match(MD5) - library["specificity"].should == "default" + expect(library["name"]).to eq("ownage.rb") + expect(library["path"]).to eq("libraries/ownage.rb") + expect(library["checksum"]).to match(MD5) + expect(library["specificity"]).to eq("default") - manifest["attributes"].should have(1).attribute_file + expect(manifest["attributes"].size).to eq(1) attribute_file = manifest["attributes"].first - attribute_file["name"].should == "default.rb" - attribute_file["path"].should == "attributes/default.rb" - attribute_file["checksum"].should match(MD5) - attribute_file["specificity"].should == "default" + expect(attribute_file["name"]).to eq("default.rb") + expect(attribute_file["path"]).to eq("attributes/default.rb") + expect(attribute_file["checksum"]).to match(MD5) + expect(attribute_file["specificity"]).to eq("default") - manifest["files"].should have(1).cookbook_file + expect(manifest["files"].size).to eq(1) cookbook_file = manifest["files"].first - cookbook_file["name"].should == "giant_blob.tgz" - cookbook_file["path"].should == "files/default/giant_blob.tgz" - cookbook_file["checksum"].should match(MD5) - cookbook_file["specificity"].should == "default" + expect(cookbook_file["name"]).to eq("giant_blob.tgz") + expect(cookbook_file["path"]).to eq("files/default/giant_blob.tgz") + expect(cookbook_file["checksum"]).to match(MD5) + expect(cookbook_file["specificity"]).to eq("default") - manifest["templates"].should have(1).template + expect(manifest["templates"].size).to eq(1) template = manifest["templates"].first - template["name"].should == "configuration.erb" - template["path"].should == "templates/default/configuration.erb" - template["checksum"].should match(MD5) - template["specificity"].should == "default" + expect(template["name"]).to eq("configuration.erb") + expect(template["path"]).to eq("templates/default/configuration.erb") + expect(template["checksum"]).to match(MD5) + expect(template["specificity"]).to eq("default") - manifest["resources"].should have(1).lwr + expect(manifest["resources"].size).to eq(1) lwr = manifest["resources"].first - lwr["name"].should == "lwr.rb" - lwr["path"].should == "resources/lwr.rb" - lwr["checksum"].should match(MD5) - lwr["specificity"].should == "default" + expect(lwr["name"]).to eq("lwr.rb") + expect(lwr["path"]).to eq("resources/lwr.rb") + expect(lwr["checksum"]).to match(MD5) + expect(lwr["specificity"]).to eq("default") - manifest["providers"].should have(1).lwp + expect(manifest["providers"].size).to eq(1) lwp = manifest["providers"].first - lwp["name"].should == "lwp.rb" - lwp["path"].should == "providers/lwp.rb" - lwp["checksum"].should match(MD5) - lwp["specificity"].should == "default" + expect(lwp["name"]).to eq("lwp.rb") + expect(lwp["path"]).to eq("providers/lwp.rb") + expect(lwp["checksum"]).to match(MD5) + expect(lwp["specificity"]).to eq("default") - manifest["root_files"].should have(1).file_in_the_cookbook_root + expect(manifest["root_files"].size).to eq(1) readme = manifest["root_files"].first - readme["name"].should == "README.rdoc" - readme["path"].should == "README.rdoc" - readme["checksum"].should match(MD5) - readme["specificity"].should == "default" + expect(readme["name"]).to eq("README.rdoc") + expect(readme["path"]).to eq("README.rdoc") + expect(readme["checksum"]).to match(MD5) + expect(readme["specificity"]).to eq("default") end end end @@ -389,43 +389,43 @@ describe Chef::CookbookVersion do end it "should see a template" do - @cookbook_version.should have_template_for_node(@node, "test.erb") + expect(@cookbook_version).to have_template_for_node(@node, "test.erb") end it "should see a template using an array lookup" do - @cookbook_version.should have_template_for_node(@node, ["test.erb"]) + expect(@cookbook_version).to have_template_for_node(@node, ["test.erb"]) end it "should see a template using an array lookup with non-existant elements" do - @cookbook_version.should have_template_for_node(@node, ["missing.txt", "test.erb"]) + expect(@cookbook_version).to have_template_for_node(@node, ["missing.txt", "test.erb"]) end it "should see a file" do - @cookbook_version.should have_cookbook_file_for_node(@node, "test.txt") + expect(@cookbook_version).to have_cookbook_file_for_node(@node, "test.txt") end it "should see a file using an array lookup" do - @cookbook_version.should have_cookbook_file_for_node(@node, ["test.txt"]) + expect(@cookbook_version).to have_cookbook_file_for_node(@node, ["test.txt"]) end it "should see a file using an array lookup with non-existant elements" do - @cookbook_version.should have_cookbook_file_for_node(@node, ["missing.txt", "test.txt"]) + expect(@cookbook_version).to have_cookbook_file_for_node(@node, ["missing.txt", "test.txt"]) end it "should not see a non-existant template" do - @cookbook_version.should_not have_template_for_node(@node, "missing.erb") + expect(@cookbook_version).not_to have_template_for_node(@node, "missing.erb") end it "should not see a non-existant template using an array lookup" do - @cookbook_version.should_not have_template_for_node(@node, ["missing.erb"]) + expect(@cookbook_version).not_to have_template_for_node(@node, ["missing.erb"]) end it "should not see a non-existant file" do - @cookbook_version.should_not have_cookbook_file_for_node(@node, "missing.txt") + expect(@cookbook_version).not_to have_cookbook_file_for_node(@node, "missing.txt") end it "should not see a non-existant file using an array lookup" do - @cookbook_version.should_not have_cookbook_file_for_node(@node, ["missing.txt"]) + expect(@cookbook_version).not_to have_cookbook_file_for_node(@node, ["missing.txt"]) end end @@ -453,9 +453,9 @@ describe Chef::CookbookVersion do lg = Chef::CookbookVersion.new("foo", '/tmp/blah') sm.version = smaller lg.version = larger - sm.should be < lg - lg.should be > sm - sm.should_not == lg + expect(sm).to be < lg + expect(lg).to be > sm + expect(sm).not_to eq(lg) end end @@ -464,7 +464,7 @@ describe Chef::CookbookVersion do b = Chef::CookbookVersion.new("foo", '/tmp/blah') a.version = "1.2" b.version = "1.2.0" - a.should == b + expect(a).to eq(b) end @@ -473,7 +473,7 @@ describe Chef::CookbookVersion do apt.version = "1.0" god = Chef::CookbookVersion.new "god", '/tmp/blah' god.version = "2.0" - lambda {apt <=> god}.should raise_error(Chef::Exceptions::CookbookVersionNameMismatch) + expect {apt <=> god}.to raise_error(Chef::Exceptions::CookbookVersionNameMismatch) end end @@ -493,7 +493,7 @@ describe Chef::CookbookVersion do "1 2 3", "1-2-3", "1_2_3", "1.2_3", "1.2-3"] the_error = Chef::Exceptions::InvalidCookbookVersion bad_versions.each do |v| - lambda {@cbv.version = v}.should raise_error(the_error) + expect {@cbv.version = v}.to raise_error(the_error) end end diff --git a/spec/unit/daemon_spec.rb b/spec/unit/daemon_spec.rb index 9132dae389..e020576a23 100644 --- a/spec/unit/daemon_spec.rb +++ b/spec/unit/daemon_spec.rb @@ -23,12 +23,12 @@ describe Chef::Daemon do if windows? mock_struct = #Struct::Passwd.new(nil, nil, 111, 111) mock_struct = OpenStruct.new(:uid => 2342, :gid => 2342) - Etc.stub(:getpwnam).and_return mock_struct - Etc.stub(:getgrnam).and_return mock_struct + allow(Etc).to receive(:getpwnam).and_return mock_struct + allow(Etc).to receive(:getgrnam).and_return mock_struct # mock unimplemented methods - Process.stub(:initgroups).and_return nil - Process::GID.stub(:change_privilege).and_return 11 - Process::UID.stub(:change_privilege).and_return 11 + allow(Process).to receive(:initgroups).and_return nil + allow(Process::GID).to receive(:change_privilege).and_return 11 + allow(Process::UID).to receive(:change_privilege).and_return 11 end end @@ -41,7 +41,7 @@ describe Chef::Daemon do end it "should return the supplied value" do - Chef::Daemon.pid_file.should eql("/var/run/chef/chef-client.pid") + expect(Chef::Daemon.pid_file).to eql("/var/run/chef/chef-client.pid") end end @@ -52,7 +52,7 @@ describe Chef::Daemon do end it "should return a valued based on @name" do - Chef::Daemon.pid_file.should eql("/tmp/chef-client.pid") + expect(Chef::Daemon.pid_file).to eql("/tmp/chef-client.pid") end end @@ -65,7 +65,7 @@ describe Chef::Daemon do end it "should suck the pid out of pid_file" do - File.should_receive(:read).with("/var/run/chef/chef-client.pid").and_return("1337") + expect(File).to receive(:read).with("/var/run/chef/chef-client.pid").and_return("1337") Chef::Daemon.pid_from_file end end @@ -73,13 +73,13 @@ describe Chef::Daemon do describe ".change_privilege" do before do - Chef::Application.stub(:fatal!).and_return(true) + allow(Chef::Application).to receive(:fatal!).and_return(true) Chef::Config[:user] = 'aj' - Dir.stub(:chdir) + allow(Dir).to receive(:chdir) end it "changes the working directory to root" do - Dir.should_receive(:chdir).with("/").and_return(0) + expect(Dir).to receive(:chdir).with("/").and_return(0) Chef::Daemon.change_privilege end @@ -90,24 +90,24 @@ describe Chef::Daemon do end it "should log an appropriate info message" do - Chef::Log.should_receive(:info).with("About to change privilege to aj:staff") + expect(Chef::Log).to receive(:info).with("About to change privilege to aj:staff") Chef::Daemon.change_privilege end it "should call _change_privilege with the user and group" do - Chef::Daemon.should_receive(:_change_privilege).with("aj", "staff") + expect(Chef::Daemon).to receive(:_change_privilege).with("aj", "staff") Chef::Daemon.change_privilege end end describe "when just the user option is supplied" do it "should log an appropriate info message" do - Chef::Log.should_receive(:info).with("About to change privilege to aj") + expect(Chef::Log).to receive(:info).with("About to change privilege to aj") Chef::Daemon.change_privilege end it "should call _change_privilege with just the user" do - Chef::Daemon.should_receive(:_change_privilege).with("aj") + expect(Chef::Daemon).to receive(:_change_privilege).with("aj") Chef::Daemon.change_privilege end end @@ -116,56 +116,56 @@ describe Chef::Daemon do describe "._change_privilege" do before do - Process.stub(:euid).and_return(0) - Process.stub(:egid).and_return(0) + allow(Process).to receive(:euid).and_return(0) + allow(Process).to receive(:egid).and_return(0) - Process::UID.stub(:change_privilege).and_return(nil) - Process::GID.stub(:change_privilege).and_return(nil) + allow(Process::UID).to receive(:change_privilege).and_return(nil) + allow(Process::GID).to receive(:change_privilege).and_return(nil) @pw_user = double("Struct::Passwd", :uid => 501) @pw_group = double("Struct::Group", :gid => 20) - Process.stub(:initgroups).and_return(true) + allow(Process).to receive(:initgroups).and_return(true) - Etc.stub(:getpwnam).and_return(@pw_user) - Etc.stub(:getgrnam).and_return(@pw_group) + allow(Etc).to receive(:getpwnam).and_return(@pw_user) + allow(Etc).to receive(:getgrnam).and_return(@pw_group) end describe "with sufficient privileges" do before do - Process.stub(:euid).and_return(0) - Process.stub(:egid).and_return(0) + allow(Process).to receive(:euid).and_return(0) + allow(Process).to receive(:egid).and_return(0) end it "should initialize the supplemental group list" do - Process.should_receive(:initgroups).with("aj", 20) + expect(Process).to receive(:initgroups).with("aj", 20) Chef::Daemon._change_privilege("aj") end it "should attempt to change the process GID" do - Process::GID.should_receive(:change_privilege).with(20).and_return(20) + expect(Process::GID).to receive(:change_privilege).with(20).and_return(20) Chef::Daemon._change_privilege("aj") end it "should attempt to change the process UID" do - Process::UID.should_receive(:change_privilege).with(501).and_return(501) + expect(Process::UID).to receive(:change_privilege).with(501).and_return(501) Chef::Daemon._change_privilege("aj") end end describe "with insufficient privileges" do before do - Process.stub(:euid).and_return(999) - Process.stub(:egid).and_return(999) + allow(Process).to receive(:euid).and_return(999) + allow(Process).to receive(:egid).and_return(999) end it "should log an appropriate error message and fail miserably" do - Process.stub(:initgroups).and_raise(Errno::EPERM) + allow(Process).to receive(:initgroups).and_raise(Errno::EPERM) error = "Operation not permitted" if RUBY_PLATFORM.match("solaris2") || RUBY_PLATFORM.match("aix") error = "Not owner" end - Chef::Application.should_receive(:fatal!).with("Permission denied when trying to change 999:999 to 501:20. #{error}") + expect(Chef::Application).to receive(:fatal!).with("Permission denied when trying to change 999:999 to 501:20. #{error}") Chef::Daemon._change_privilege("aj") end end diff --git a/spec/unit/data_bag_item_spec.rb b/spec/unit/data_bag_item_spec.rb index 5972d8a239..4cf6e59242 100644 --- a/spec/unit/data_bag_item_spec.rb +++ b/spec/unit/data_bag_item_spec.rb @@ -26,69 +26,69 @@ describe Chef::DataBagItem do describe "initialize" do it "should be a Chef::DataBagItem" do - @data_bag_item.should be_a_kind_of(Chef::DataBagItem) + expect(@data_bag_item).to be_a_kind_of(Chef::DataBagItem) end end describe "data_bag" do it "should let you set the data_bag to a string" do - @data_bag_item.data_bag("clowns").should == "clowns" + expect(@data_bag_item.data_bag("clowns")).to eq("clowns") end it "should return the current data_bag type" do @data_bag_item.data_bag "clowns" - @data_bag_item.data_bag.should == "clowns" + expect(@data_bag_item.data_bag).to eq("clowns") end it "should not accept spaces" do - lambda { @data_bag_item.data_bag "clown masters" }.should raise_error(ArgumentError) + expect { @data_bag_item.data_bag "clown masters" }.to raise_error(ArgumentError) end it "should throw an ArgumentError if you feed it anything but a string" do - lambda { @data_bag_item.data_bag Hash.new }.should raise_error(ArgumentError) + expect { @data_bag_item.data_bag Hash.new }.to raise_error(ArgumentError) end end describe "raw_data" do it "should let you set the raw_data with a hash" do - lambda { @data_bag_item.raw_data = { "id" => "octahedron" } }.should_not raise_error + expect { @data_bag_item.raw_data = { "id" => "octahedron" } }.not_to raise_error end it "should let you set the raw_data from a mash" do - lambda { @data_bag_item.raw_data = Mash.new({ "id" => "octahedron" }) }.should_not raise_error + expect { @data_bag_item.raw_data = Mash.new({ "id" => "octahedron" }) }.not_to raise_error end it "should raise an exception if you set the raw data without a key" do - lambda { @data_bag_item.raw_data = { "monkey" => "pants" } }.should raise_error(ArgumentError) + expect { @data_bag_item.raw_data = { "monkey" => "pants" } }.to raise_error(ArgumentError) end it "should raise an exception if you set the raw data to something other than a hash" do - lambda { @data_bag_item.raw_data = "katie rules" }.should raise_error(ArgumentError) + expect { @data_bag_item.raw_data = "katie rules" }.to raise_error(ArgumentError) end it "should accept alphanum/-/_ for the id" do - lambda { @data_bag_item.raw_data = { "id" => "h1-_" } }.should_not raise_error + expect { @data_bag_item.raw_data = { "id" => "h1-_" } }.not_to raise_error end it "should accept alphanum.alphanum for the id" do - lambda { @data_bag_item.raw_data = { "id" => "foo.bar" } }.should_not raise_error + expect { @data_bag_item.raw_data = { "id" => "foo.bar" } }.not_to raise_error end it "should accept .alphanum for the id" do - lambda { @data_bag_item.raw_data = { "id" => ".bozo" } }.should_not raise_error + expect { @data_bag_item.raw_data = { "id" => ".bozo" } }.not_to raise_error end it "should raise an exception if the id contains anything but alphanum/-/_" do - lambda { @data_bag_item.raw_data = { "id" => "!@#" } }.should raise_error(ArgumentError) + expect { @data_bag_item.raw_data = { "id" => "!@#" } }.to raise_error(ArgumentError) end it "should return the raw data" do @data_bag_item.raw_data = { "id" => "highway_of_emptiness" } - @data_bag_item.raw_data.should == { "id" => "highway_of_emptiness" } + expect(@data_bag_item.raw_data).to eq({ "id" => "highway_of_emptiness" }) end it "should be a Mash by default" do - @data_bag_item.raw_data.should be_a_kind_of(Mash) + expect(@data_bag_item.raw_data).to be_a_kind_of(Mash) end end @@ -99,13 +99,13 @@ describe Chef::DataBagItem do end it "should return an object name based on the bag name and the raw_data id" do - @data_bag_item.object_name.should == "data_bag_item_dreams_the_beatdown" + expect(@data_bag_item.object_name).to eq("data_bag_item_dreams_the_beatdown") end end describe "class method object_name" do it "should return an object name based based on the bag name and an id" do - Chef::DataBagItem.object_name("zen", "master").should == "data_bag_item_zen_master" + expect(Chef::DataBagItem.object_name("zen", "master")).to eq("data_bag_item_zen_master") end end @@ -115,12 +115,12 @@ describe Chef::DataBagItem do end it "responds to keys" do - @data_bag_item.keys.should include("id") - @data_bag_item.keys.should include("trials") + expect(@data_bag_item.keys).to include("id") + expect(@data_bag_item.keys).to include("trials") end it "supports element reference with []" do - @data_bag_item["id"].should == "journey" + expect(@data_bag_item["id"]).to eq("journey") end it "implements all the methods of Hash" do @@ -131,7 +131,7 @@ describe Chef::DataBagItem do :invert, :update, :replace, :merge!, :merge, :has_key?, :has_value?, :key?, :value?] methods.each do |m| - @data_bag_item.should respond_to(m) + expect(@data_bag_item).to respond_to(m) end end @@ -145,20 +145,20 @@ describe Chef::DataBagItem do end it "should return a hash" do - @to_hash.should be_a_kind_of(Hash) + expect(@to_hash).to be_a_kind_of(Hash) end it "should have the raw_data keys as top level keys" do - @to_hash["id"].should == "whoa" - @to_hash["i_know"].should == "kung_fu" + expect(@to_hash["id"]).to eq("whoa") + expect(@to_hash["i_know"]).to eq("kung_fu") end it "should have the chef_type of data_bag_item" do - @to_hash["chef_type"].should == "data_bag_item" + expect(@to_hash["chef_type"]).to eq("data_bag_item") end it "should have the data_bag set" do - @to_hash["data_bag"].should == "still_lost" + expect(@to_hash["data_bag"]).to eq("still_lost") end end @@ -170,19 +170,19 @@ describe Chef::DataBagItem do end it "should deserialize to a Chef::DataBagItem object" do - @deserial.should be_a_kind_of(Chef::DataBagItem) + expect(@deserial).to be_a_kind_of(Chef::DataBagItem) end it "should have a matching 'data_bag' value" do - @deserial.data_bag.should == @data_bag_item.data_bag + expect(@deserial.data_bag).to eq(@data_bag_item.data_bag) end it "should have a matching 'id' key" do - @deserial["id"].should == "octahedron" + expect(@deserial["id"]).to eq("octahedron") end it "should have a matching 'snooze' key" do - @deserial["snooze"].should == { "finally" => "world_will" } + expect(@deserial["snooze"]).to eq({ "finally" => "world_will" }) end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -193,7 +193,7 @@ describe Chef::DataBagItem do describe "when converting to a string" do it "converts to a string in the form data_bag_item[ID]" do @data_bag_item['id'] = "heart of darkness" - @data_bag_item.to_s.should == 'data_bag_item[heart of darkness]' + expect(@data_bag_item.to_s).to eq('data_bag_item[heart of darkness]') end it "inspects as data_bag_item[BAG, ID, RAW_DATA]" do @@ -201,28 +201,28 @@ describe Chef::DataBagItem do @data_bag_item.raw_data = raw_data @data_bag_item.data_bag("books") - @data_bag_item.inspect.should == "data_bag_item[\"books\", \"heart_of_darkness\", #{raw_data.inspect}]" + expect(@data_bag_item.inspect).to eq("data_bag_item[\"books\", \"heart_of_darkness\", #{raw_data.inspect}]") end end describe "save" do before do @rest = double("Chef::REST") - Chef::REST.stub(:new).and_return(@rest) + allow(Chef::REST).to receive(:new).and_return(@rest) @data_bag_item['id'] = "heart of darkness" raw_data = {"id" => "heart_of_darkness", "author" => "Conrad"} @data_bag_item.raw_data = raw_data @data_bag_item.data_bag("books") end it "should update the item when it already exists" do - @rest.should_receive(:put_rest).with("data/books/heart_of_darkness", @data_bag_item) + expect(@rest).to receive(:put_rest).with("data/books/heart_of_darkness", @data_bag_item) @data_bag_item.save end it "should create if the item is not found" do exception = double("404 error", :code => "404") - @rest.should_receive(:put_rest).and_raise(Net::HTTPServerException.new("foo", exception)) - @rest.should_receive(:post_rest).with("data/books", @data_bag_item) + expect(@rest).to receive(:put_rest).and_raise(Net::HTTPServerException.new("foo", exception)) + expect(@rest).to receive(:post_rest).with("data/books", @data_bag_item) @data_bag_item.save end describe "when whyrun mode is enabled" do @@ -233,8 +233,8 @@ describe Chef::DataBagItem do Chef::Config[:why_run] = false end it "should not save" do - @rest.should_not_receive(:put_rest) - @rest.should_not_receive(:post_rest) + expect(@rest).not_to receive(:put_rest) + expect(@rest).not_to receive(:post_rest) @data_bag_item.data_bag("books") @data_bag_item.save end @@ -252,21 +252,21 @@ describe Chef::DataBagItem do describe "from an API call" do before do @http_client = double("Chef::REST") - Chef::REST.stub(:new).and_return(@http_client) + allow(Chef::REST).to receive(:new).and_return(@http_client) end it "converts raw data to a data bag item" do - @http_client.should_receive(:get_rest).with("data/users/charlie").and_return(@data_bag_item.to_hash) + expect(@http_client).to receive(:get_rest).with("data/users/charlie").and_return(@data_bag_item.to_hash) item = Chef::DataBagItem.load(:users, "charlie") - item.should be_a_kind_of(Chef::DataBagItem) - item.should == @data_bag_item + expect(item).to be_a_kind_of(Chef::DataBagItem) + expect(item).to eq(@data_bag_item) end it "does not convert when a DataBagItem is returned from the API call" do - @http_client.should_receive(:get_rest).with("data/users/charlie").and_return(@data_bag_item) + expect(@http_client).to receive(:get_rest).with("data/users/charlie").and_return(@data_bag_item) item = Chef::DataBagItem.load(:users, "charlie") - item.should be_a_kind_of(Chef::DataBagItem) - item.should equal(@data_bag_item) + expect(item).to be_a_kind_of(Chef::DataBagItem) + expect(item).to equal(@data_bag_item) end end @@ -280,10 +280,10 @@ describe Chef::DataBagItem do end it "converts the raw data to a data bag item" do - Chef::DataBag.should_receive(:load).with('users').and_return({'charlie' => @data_bag_item.to_hash}) + expect(Chef::DataBag).to receive(:load).with('users').and_return({'charlie' => @data_bag_item.to_hash}) item = Chef::DataBagItem.load('users', 'charlie') - item.should be_a_kind_of(Chef::DataBagItem) - item.should == @data_bag_item + expect(item).to be_a_kind_of(Chef::DataBagItem) + expect(item).to eq(@data_bag_item) end end diff --git a/spec/unit/data_bag_spec.rb b/spec/unit/data_bag_spec.rb index ff323902eb..f6db1e222a 100644 --- a/spec/unit/data_bag_spec.rb +++ b/spec/unit/data_bag_spec.rb @@ -22,36 +22,36 @@ require 'chef/data_bag' describe Chef::DataBag do before(:each) do @data_bag = Chef::DataBag.new - Chef::Platform::stub(:windows?) { false } + allow(Chef::Platform)::to receive(:windows?) { false } end describe "initialize" do it "should be a Chef::DataBag" do - @data_bag.should be_a_kind_of(Chef::DataBag) + expect(@data_bag).to be_a_kind_of(Chef::DataBag) end end describe "name" do it "should let you set the name to a string" do - @data_bag.name("clowns").should == "clowns" + expect(@data_bag.name("clowns")).to eq("clowns") end it "should return the current name" do @data_bag.name "clowns" - @data_bag.name.should == "clowns" + expect(@data_bag.name).to eq("clowns") end it "should not accept spaces" do - lambda { @data_bag.name "clown masters" }.should raise_error(ArgumentError) + expect { @data_bag.name "clown masters" }.to raise_error(ArgumentError) end it "should throw an ArgumentError if you feed it anything but a string" do - lambda { @data_bag.name Hash.new }.should raise_error(ArgumentError) + expect { @data_bag.name Hash.new }.to raise_error(ArgumentError) end [ ".", "-", "_", "1"].each do |char| it "should allow a '#{char}' character in the data bag name" do - @data_bag.name("clown#{char}clown").should == "clown#{char}clown" + expect(@data_bag.name("clown#{char}clown")).to eq("clown#{char}clown") end end end @@ -63,14 +63,14 @@ describe Chef::DataBag do end it "should deserialize to a Chef::DataBag object" do - @deserial.should be_a_kind_of(Chef::DataBag) + expect(@deserial).to be_a_kind_of(Chef::DataBag) end %w{ name }.each do |t| it "should match '#{t}'" do - @deserial.send(t.to_sym).should == @data_bag.send(t.to_sym) + expect(@deserial.send(t.to_sym)).to eq(@data_bag.send(t.to_sym)) end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -84,17 +84,17 @@ describe Chef::DataBag do before do @data_bag.name('piggly_wiggly') @rest = double("Chef::REST") - Chef::REST.stub(:new).and_return(@rest) + allow(Chef::REST).to receive(:new).and_return(@rest) end it "should silently proceed when the data bag already exists" do exception = double("409 error", :code => "409") - @rest.should_receive(:post_rest).and_raise(Net::HTTPServerException.new("foo", exception)) + expect(@rest).to receive(:post_rest).and_raise(Net::HTTPServerException.new("foo", exception)) @data_bag.save end it "should create the data bag" do - @rest.should_receive(:post_rest).with("data", @data_bag) + expect(@rest).to receive(:post_rest).with("data", @data_bag) @data_bag.save end @@ -106,7 +106,7 @@ describe Chef::DataBag do Chef::Config[:why_run] = false end it "should not save" do - @rest.should_not_receive(:post_rest) + expect(@rest).not_to receive(:post_rest) @data_bag.save end end @@ -120,25 +120,25 @@ describe Chef::DataBag do end it "should get the data bag from the server" do - Chef::REST.should_receive(:new).with('https://myserver.example.com').and_return(@http_client) - @http_client.should_receive(:get_rest).with('data/foo') + expect(Chef::REST).to receive(:new).with('https://myserver.example.com').and_return(@http_client) + expect(@http_client).to receive(:get_rest).with('data/foo') Chef::DataBag.load('foo') end it "should return the data bag" do - Chef::REST.stub(:new).and_return(@http_client) - @http_client.should_receive(:get_rest).with('data/foo').and_return({'bar' => 'https://myserver.example.com/data/foo/bar'}) + allow(Chef::REST).to receive(:new).and_return(@http_client) + expect(@http_client).to receive(:get_rest).with('data/foo').and_return({'bar' => 'https://myserver.example.com/data/foo/bar'}) data_bag = Chef::DataBag.load('foo') - data_bag.should == {'bar' => 'https://myserver.example.com/data/foo/bar'} + expect(data_bag).to eq({'bar' => 'https://myserver.example.com/data/foo/bar'}) end end def file_dir_stub(path, returns = true) - File.should_receive(:directory?).with(path).and_return(returns) + expect(File).to receive(:directory?).with(path).and_return(returns) end def dir_glob_stub(path, returns = []) - Dir.should_receive(:glob).with(File.join(path, 'foo/*.json')).and_return(returns) + expect(Dir).to receive(:glob).with(File.join(path, 'foo/*.json')).and_return(returns) end shared_examples_for "data bag in solo mode" do |data_bag_path| @@ -177,21 +177,21 @@ describe Chef::DataBag do dir_glob_stub(path) end end - IO.should_receive(:read).with(File.join(@paths.first, 'foo/bar.json')).and_return('{"id": "bar", "name": "Bob Bar" }') - IO.should_receive(:read).with(File.join(@paths.first, 'foo/baz.json')).and_return('{"id": "baz", "name": "John Baz" }') + expect(IO).to receive(:read).with(File.join(@paths.first, 'foo/bar.json')).and_return('{"id": "bar", "name": "Bob Bar" }') + expect(IO).to receive(:read).with(File.join(@paths.first, 'foo/baz.json')).and_return('{"id": "baz", "name": "John Baz" }') data_bag = Chef::DataBag.load('foo') - data_bag.should == { 'bar' => { 'id' => 'bar', 'name' => 'Bob Bar' }, 'baz' => { 'id' => 'baz', 'name' => 'John Baz' }} + expect(data_bag).to eq({ 'bar' => { 'id' => 'bar', 'name' => 'Bob Bar' }, 'baz' => { 'id' => 'baz', 'name' => 'John Baz' }}) end it "should raise if data bag has items with similar names but different content" do @paths.each do |path| file_dir_stub(path) item_with_different_content = "{\"id\": \"bar\", \"name\": \"Bob Bar\", \"path\": \"#{path}\"}" - IO.should_receive(:read).with(File.join(path, 'foo/bar.json')).and_return(item_with_different_content) + expect(IO).to receive(:read).with(File.join(path, 'foo/bar.json')).and_return(item_with_different_content) if data_bag_path.is_a?(String) dir_glob_stub(path, [File.join(path, 'foo/bar.json'), File.join(path, 'foo/baz.json')]) item_2_with_different_content = '{"id": "bar", "name": "John Baz"}' - IO.should_receive(:read).with(File.join(path, 'foo/baz.json')).and_return(item_2_with_different_content) + expect(IO).to receive(:read).with(File.join(path, 'foo/baz.json')).and_return(item_2_with_different_content) else dir_glob_stub(path, [File.join(path, 'foo/bar.json')]) end @@ -204,12 +204,12 @@ describe Chef::DataBag do file_dir_stub(path) dir_glob_stub(path, [File.join(path, 'foo/bar.json'), File.join(path, 'foo/baz.json')]) item_with_same_content = '{"id": "bar", "name": "Bob Bar"}' - IO.should_receive(:read).with(File.join(path, 'foo/bar.json')).and_return(item_with_same_content) - IO.should_receive(:read).with(File.join(path, 'foo/baz.json')).and_return(item_with_same_content) + expect(IO).to receive(:read).with(File.join(path, 'foo/bar.json')).and_return(item_with_same_content) + expect(IO).to receive(:read).with(File.join(path, 'foo/baz.json')).and_return(item_with_same_content) end data_bag = Chef::DataBag.load('foo') test_data_bag = { 'bar' => { 'id' => 'bar', 'name' => 'Bob Bar'} } - data_bag.should == test_data_bag + expect(data_bag).to eq(test_data_bag) end it "should merge data bag items if there are no conflicts" do @@ -217,33 +217,33 @@ describe Chef::DataBag do file_dir_stub(path) dir_glob_stub(path, [File.join(path, 'foo/bar.json'), File.join(path, 'foo/baz.json')]) test_item_with_same_content = '{"id": "bar", "name": "Bob Bar"}' - IO.should_receive(:read).with(File.join(path, 'foo/bar.json')).and_return(test_item_with_same_content) + expect(IO).to receive(:read).with(File.join(path, 'foo/bar.json')).and_return(test_item_with_same_content) test_uniq_item = "{\"id\": \"baz_#{index}\", \"name\": \"John Baz\", \"path\": \"#{path}\"}" - IO.should_receive(:read).with(File.join(path, 'foo/baz.json')).and_return(test_uniq_item) + expect(IO).to receive(:read).with(File.join(path, 'foo/baz.json')).and_return(test_uniq_item) end data_bag = Chef::DataBag.load('foo') test_data_bag = { 'bar' => { 'id' => 'bar', 'name' => 'Bob Bar'} } @paths.each_with_index do |path, index| test_data_bag["baz_#{index}"] = { "id" => "baz_#{index}", "name" => "John Baz", "path" => path } end - data_bag.should == test_data_bag + expect(data_bag).to eq(test_data_bag) end it "should return the data bag list" do @paths.each do |path| file_dir_stub(path) - Dir.should_receive(:glob).and_return([File.join(path, 'foo'), File.join(path, 'bar')]) + expect(Dir).to receive(:glob).and_return([File.join(path, 'foo'), File.join(path, 'bar')]) end data_bag_list = Chef::DataBag.list - data_bag_list.should == { 'bar' => 'bar', 'foo' => 'foo' } + expect(data_bag_list).to eq({ 'bar' => 'bar', 'foo' => 'foo' }) end it 'should raise an error if the configured data_bag_path is invalid' do file_dir_stub(@paths.first, false) - lambda { + expect { Chef::DataBag.load('foo') - }.should raise_error Chef::Exceptions::InvalidDataBagPath, "Data bag path '/var/chef/data_bags' is invalid" + }.to raise_error Chef::Exceptions::InvalidDataBagPath, "Data bag path '/var/chef/data_bags' is invalid" end end diff --git a/spec/unit/deprecation_spec.rb b/spec/unit/deprecation_spec.rb index c5ab41fbab..9bd081a6c4 100644 --- a/spec/unit/deprecation_spec.rb +++ b/spec/unit/deprecation_spec.rb @@ -54,7 +54,7 @@ describe Chef::Deprecation do it "defines all methods on #{class_object} that were available in 11.0" do old_methods.each do |old_method| - current_methods.should include(old_method.to_sym) + expect(current_methods).to include(old_method.to_sym) end end end @@ -62,24 +62,24 @@ describe Chef::Deprecation do context 'deprecation warning messages' do before(:each) do @warning_output = [ ] - Chef::Log.stub(:warn) { |msg| @warning_output << msg } + allow(Chef::Log).to receive(:warn) { |msg| @warning_output << msg } end it 'should be enabled for deprecated methods' do TestClass.new.deprecated_method(10) - @warning_output.should_not be_empty + expect(@warning_output).not_to be_empty end it 'should contain stack trace' do TestClass.new.deprecated_method(10) - @warning_output.join("").include?(".rb").should be_true + expect(@warning_output.join("").include?(".rb")).to be_truthy end end it 'deprecated methods should still be called' do test_instance = TestClass.new test_instance.deprecated_method(10) - test_instance.get_value.should == 10 + expect(test_instance.get_value).to eq(10) end end diff --git a/spec/unit/digester_spec.rb b/spec/unit/digester_spec.rb index fdf20aca7c..51bcfbdde5 100644 --- a/spec/unit/digester_spec.rb +++ b/spec/unit/digester_spec.rb @@ -28,20 +28,20 @@ describe Chef::Digester do describe "when computing checksums of cookbook files and templates" do it "proxies the class method checksum_for_file to the instance" do - @cache.should_receive(:checksum_for_file).with("a_file_or_a_fail") + expect(@cache).to receive(:checksum_for_file).with("a_file_or_a_fail") Chef::Digester.checksum_for_file("a_file_or_a_fail") end it "computes a checksum of a file" do fixture_file = CHEF_SPEC_DATA + "/checksum/random.txt" expected = "09ee9c8cc70501763563bcf9c218d71b2fbf4186bf8e1e0da07f0f42c80a3394" - @cache.checksum_for_file(fixture_file).should == expected + expect(@cache.checksum_for_file(fixture_file)).to eq(expected) end it "generates a checksum from a non-file IO object" do io = StringIO.new("riseofthemachines\nriseofthechefs\n") expected_md5 = '0e157ac1e2dd73191b76067fb6b4bceb' - @cache.generate_md5_checksum(io).should == expected_md5 + expect(@cache.generate_md5_checksum(io)).to eq(expected_md5) end end diff --git a/spec/unit/dsl/data_query_spec.rb b/spec/unit/dsl/data_query_spec.rb index 78cd5569e8..b93ae1f1d6 100644 --- a/spec/unit/dsl/data_query_spec.rb +++ b/spec/unit/dsl/data_query_spec.rb @@ -28,7 +28,7 @@ describe Chef::DSL::DataQuery do let(:language) do language = DataQueryDSLTester.new - language.stub(:node).and_return(@node) + allow(language).to receive(:node).and_return(@node) language end diff --git a/spec/unit/dsl/platform_introspection_spec.rb b/spec/unit/dsl/platform_introspection_spec.rb index f00d5a2ab8..e41560c034 100644 --- a/spec/unit/dsl/platform_introspection_spec.rb +++ b/spec/unit/dsl/platform_introspection_spec.rb @@ -48,37 +48,37 @@ describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do end it "returns the default value when the platform doesn't match" do - @platform_specific_value.value_for_node(:platform => :dos).should == 'bork da bork' + expect(@platform_specific_value.value_for_node(:platform => :dos)).to eq('bork da bork') end it "returns a value for a platform set as a group" do - @platform_specific_value.value_for_node(:platform => :centos).should == '"stable"' + expect(@platform_specific_value.value_for_node(:platform => :centos)).to eq('"stable"') end it "returns a value for the platform when it was set as a symbol but fetched as a string" do - @platform_specific_value.value_for_node(:platform => "centos").should == '"stable"' + expect(@platform_specific_value.value_for_node(:platform => "centos")).to eq('"stable"') end it "returns a value for a specific platform version" do node = {:platform => 'ubuntu', :platform_version => '10.04'} - @platform_specific_value.value_for_node(node).should == 'using upstart more' + expect(@platform_specific_value.value_for_node(node)).to eq('using upstart more') end it "returns a platform-default value if the platform version doesn't match an explicit one" do node = {:platform => 'ubuntu', :platform_version => '9.10' } - @platform_specific_value.value_for_node(node).should == 'using init more' + expect(@platform_specific_value.value_for_node(node)).to eq('using init more') end it "returns nil if there is no default and no platforms match" do # this matches the behavior in the original implementation. # whether or not it's correct is another matter. platform_specific_value = Chef::DSL::PlatformIntrospection::PlatformDependentValue.new({}) - platform_specific_value.value_for_node(:platform => 'foo').should be_nil + expect(platform_specific_value.value_for_node(:platform => 'foo')).to be_nil end it "raises an argument error if the platform hash is not correctly structured" do bad_hash = {:ubuntu => :foo} # should be :ubuntu => {:default => 'foo'} - lambda {Chef::DSL::PlatformIntrospection::PlatformDependentValue.new(bad_hash)}.should raise_error(ArgumentError) + expect {Chef::DSL::PlatformIntrospection::PlatformDependentValue.new(bad_hash)}.to raise_error(ArgumentError) end end @@ -98,33 +98,33 @@ describe Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue do end it "returns the default value when the platform family doesn't match" do - @platform_family_value.value_for_node(:platform_family => :os2).should == 'default value' + expect(@platform_family_value.value_for_node(:platform_family => :os2)).to eq('default value') end it "returns a value for the platform family when it was set as a string but fetched as a symbol" do - @platform_family_value.value_for_node(:platform_family => :debian).should == "debian value" + expect(@platform_family_value.value_for_node(:platform_family => :debian)).to eq("debian value") end it "returns a value for the platform family when it was set as a symbol but fetched as a string" do - @platform_family_value.value_for_node(:platform_family => "gentoo").should == "gentoo value" + expect(@platform_family_value.value_for_node(:platform_family => "gentoo")).to eq("gentoo value") end it "returns an array value stored for a platform family" do - @platform_family_value.value_for_node(:platform_family => "suse").should == @array_values + expect(@platform_family_value.value_for_node(:platform_family => "suse")).to eq(@array_values) end it "returns a value for the platform family when it was set within an array hash key as a symbol" do - @platform_family_value.value_for_node(:platform_family => :rhel).should == "redhatty value" + expect(@platform_family_value.value_for_node(:platform_family => :rhel)).to eq("redhatty value") end it "returns a value for the platform family when it was set within an array hash key as a string" do - @platform_family_value.value_for_node(:platform_family => "fedora").should == "redhatty value" + expect(@platform_family_value.value_for_node(:platform_family => "fedora")).to eq("redhatty value") end it "returns nil if there is no default and no platforms match" do platform_specific_value = Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue.new({}) - platform_specific_value.value_for_node(:platform_family => 'foo').should be_nil + expect(platform_specific_value.value_for_node(:platform_family => 'foo')).to be_nil end end diff --git a/spec/unit/dsl/reboot_pending_spec.rb b/spec/unit/dsl/reboot_pending_spec.rb index 0d643514e0..0f2288740f 100644 --- a/spec/unit/dsl/reboot_pending_spec.rb +++ b/spec/unit/dsl/reboot_pending_spec.rb @@ -25,52 +25,52 @@ describe Chef::DSL::RebootPending do let(:recipe) { Object.new.extend(Chef::DSL::RebootPending) } before do - recipe.stub(:platform?).and_return(false) + allow(recipe).to receive(:platform?).and_return(false) end context "platform is windows" do before do - recipe.stub(:platform?).with('windows').and_return(true) - recipe.stub(:registry_key_exists?).and_return(false) - recipe.stub(:registry_value_exists?).and_return(false) + allow(recipe).to receive(:platform?).with('windows').and_return(true) + allow(recipe).to receive(:registry_key_exists?).and_return(false) + allow(recipe).to receive(:registry_value_exists?).and_return(false) end it 'should return true if "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations" exists' do - recipe.stub(:registry_value_exists?).with('HKLM\SYSTEM\CurrentControlSet\Control\Session Manager', { :name => 'PendingFileRenameOperations' }).and_return(true) - expect(recipe.reboot_pending?).to be_true + allow(recipe).to receive(:registry_value_exists?).with('HKLM\SYSTEM\CurrentControlSet\Control\Session Manager', { :name => 'PendingFileRenameOperations' }).and_return(true) + expect(recipe.reboot_pending?).to be_truthy end it 'should return true if "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" exists' do - recipe.stub(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired').and_return(true) - expect(recipe.reboot_pending?).to be_true + allow(recipe).to receive(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired').and_return(true) + expect(recipe.reboot_pending?).to be_truthy end it 'should return true if key "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootRequired" exists' do - recipe.stub(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootRequired').and_return(true) - expect(recipe.reboot_pending?).to be_true + allow(recipe).to receive(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootRequired').and_return(true) + expect(recipe.reboot_pending?).to be_truthy end it 'should return true if value "HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile" contains specific data' do - recipe.stub(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').and_return(true) - recipe.stub(:registry_get_values).with('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').and_return( + allow(recipe).to receive(:registry_key_exists?).with('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').and_return(true) + allow(recipe).to receive(:registry_get_values).with('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile').and_return( [{:name => "Flags", :type => :dword, :data => 3}]) - expect(recipe.reboot_pending?).to be_true + expect(recipe.reboot_pending?).to be_truthy end end context "platform is ubuntu" do before do - recipe.stub(:platform?).with('ubuntu').and_return(true) + allow(recipe).to receive(:platform?).with('ubuntu').and_return(true) end it 'should return true if /var/run/reboot-required exists' do - File.stub(:exists?).with('/var/run/reboot-required').and_return(true) - expect(recipe.reboot_pending?).to be_true + allow(File).to receive(:exists?).with('/var/run/reboot-required').and_return(true) + expect(recipe.reboot_pending?).to be_truthy end it 'should return false if /var/run/reboot-required does not exist' do - File.stub(:exists?).with('/var/run/reboot-required').and_return(false) - expect(recipe.reboot_pending?).to be_false + allow(File).to receive(:exists?).with('/var/run/reboot-required').and_return(false) + expect(recipe.reboot_pending?).to be_falsey end end diff --git a/spec/unit/dsl/regsitry_helper_spec.rb b/spec/unit/dsl/regsitry_helper_spec.rb index 7fe08e310f..6508a12b6f 100644 --- a/spec/unit/dsl/regsitry_helper_spec.rb +++ b/spec/unit/dsl/regsitry_helper_spec.rb @@ -33,22 +33,22 @@ describe Chef::Resource::RegistryKey do context "tests registry dsl" do it "resource can access registry_helper method registry_key_exists" do - @resource.respond_to?('registry_key_exists?').should == true + expect(@resource.respond_to?('registry_key_exists?')).to eq(true) end it "resource can access registry_helper method registry_get_values" do - @resource.respond_to?('registry_get_values').should == true + expect(@resource.respond_to?('registry_get_values')).to eq(true) end it "resource can access registry_helper method registry_has_subkey" do - @resource.respond_to?('registry_has_subkeys?').should == true + expect(@resource.respond_to?('registry_has_subkeys?')).to eq(true) end it "resource can access registry_helper method registry_get_subkeys" do - @resource.respond_to?('registry_get_subkeys').should == true + expect(@resource.respond_to?('registry_get_subkeys')).to eq(true) end it "resource can access registry_helper method registry_value_exists" do - @resource.respond_to?('registry_value_exists?').should == true + expect(@resource.respond_to?('registry_value_exists?')).to eq(true) end it "resource can access registry_helper method data_value_exists" do - @resource.respond_to?('registry_data_exists?').should == true + expect(@resource.respond_to?('registry_data_exists?')).to eq(true) end end end diff --git a/spec/unit/encrypted_data_bag_item_spec.rb b/spec/unit/encrypted_data_bag_item_spec.rb index 499fabdcf9..14afea507c 100644 --- a/spec/unit/encrypted_data_bag_item_spec.rb +++ b/spec/unit/encrypted_data_bag_item_spec.rb @@ -39,7 +39,7 @@ describe Chef::EncryptedDataBagItem::Encryptor do let(:key) { "passwd" } it "encrypts to format version 1 by default" do - encryptor.should be_a_instance_of(Chef::EncryptedDataBagItem::Encryptor::Version1Encryptor) + expect(encryptor).to be_a_instance_of(Chef::EncryptedDataBagItem::Encryptor::Version1Encryptor) end describe "generating a random IV" do @@ -49,14 +49,14 @@ describe Chef::EncryptedDataBagItem::Encryptor do # No API in ruby OpenSSL to get the iv is used for the encryption back # out. Instead we test if the encrypted data is the same. If it *is* the # same, we assume the IV was the same each time. - encryptor.encrypted_data.should_not eq encryptor2.encrypted_data + expect(encryptor.encrypted_data).not_to eq encryptor2.encrypted_data end end describe "when encrypting a non-hash non-array value" do let(:plaintext_data) { 5 } it "serializes the value in a de-serializable way" do - Chef::JSONCompat.from_json(encryptor.serialized_data)["json_wrapper"].should eq 5 + expect(Chef::JSONCompat.from_json(encryptor.serialized_data)["json_wrapper"]).to eq 5 end end @@ -64,10 +64,10 @@ describe Chef::EncryptedDataBagItem::Encryptor do describe "wrapping secret values in an envelope" do it "wraps the encrypted data in an envelope with the iv and version" do final_data = encryptor.for_encrypted_item - final_data["encrypted_data"].should eq encryptor.encrypted_data - final_data["iv"].should eq Base64.encode64(encryptor.iv) - final_data["version"].should eq 1 - final_data["cipher"].should eq"aes-256-cbc" + expect(final_data["encrypted_data"]).to eq encryptor.encrypted_data + expect(final_data["iv"]).to eq Base64.encode64(encryptor.iv) + expect(final_data["version"]).to eq 1 + expect(final_data["cipher"]).to eq"aes-256-cbc" end end @@ -78,17 +78,17 @@ describe Chef::EncryptedDataBagItem::Encryptor do end it "creates a version 2 encryptor" do - encryptor.should be_a_instance_of(Chef::EncryptedDataBagItem::Encryptor::Version2Encryptor) + expect(encryptor).to be_a_instance_of(Chef::EncryptedDataBagItem::Encryptor::Version2Encryptor) end it "generates an hmac based on ciphertext with different iv" do encryptor2 = Chef::EncryptedDataBagItem::Encryptor.new(plaintext_data, key) - encryptor.hmac.should_not eq(encryptor2.hmac) + expect(encryptor.hmac).not_to eq(encryptor2.hmac) end it "includes the hmac in the envelope" do final_data = encryptor.for_encrypted_item - final_data["hmac"].should eq(encryptor.hmac) + expect(final_data["hmac"]).to eq(encryptor.hmac) end end @@ -100,23 +100,23 @@ describe Chef::EncryptedDataBagItem::Encryptor do context "on supported platforms", :aes_256_gcm_only, :ruby_20_only do it "creates a version 3 encryptor" do - encryptor.should be_a_instance_of(Chef::EncryptedDataBagItem::Encryptor::Version3Encryptor) + expect(encryptor).to be_a_instance_of(Chef::EncryptedDataBagItem::Encryptor::Version3Encryptor) end it "generates different authentication tags" do encryptor3 = Chef::EncryptedDataBagItem::Encryptor.new(plaintext_data, key) encryptor.for_encrypted_item # required to generate the auth_tag encryptor3.for_encrypted_item - encryptor.auth_tag.should_not eq(encryptor3.auth_tag) + expect(encryptor.auth_tag).not_to eq(encryptor3.auth_tag) end it "includes the auth_tag in the envelope" do final_data = encryptor.for_encrypted_item - final_data["auth_tag"].should eq(Base64::encode64(encryptor.auth_tag)) + expect(final_data["auth_tag"]).to eq(Base64::encode64(encryptor.auth_tag)) end it "throws an error if auth tag is read before encrypting the data" do - lambda { encryptor.auth_tag }.should raise_error(Chef::EncryptedDataBagItem::EncryptionFailure) + expect { encryptor.auth_tag }.to raise_error(Chef::EncryptedDataBagItem::EncryptionFailure) end end # context on supported platforms @@ -126,24 +126,24 @@ describe Chef::EncryptedDataBagItem::Encryptor do it "throws an error warning about the Ruby version if it has no GCM support" do # Force OpenSSL with AEAD support - OpenSSL::Cipher.stub(:ciphers).and_return([ aead_algorithm ]) + allow(OpenSSL::Cipher).to receive(:ciphers).and_return([ aead_algorithm ]) # Ruby without AEAD support - OpenSSL::Cipher.should_receive(:method_defined?).with(:auth_data=).and_return(false) - lambda { encryptor }.should raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires Ruby/) + expect(OpenSSL::Cipher).to receive(:method_defined?).with(:auth_data=).and_return(false) + expect { encryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires Ruby/) end it "throws an error warning about the OpenSSL version if it has no GCM support" do # Force Ruby with AEAD support - OpenSSL::Cipher.stub(:method_defined?).with(:auth_data=).and_return(true) + allow(OpenSSL::Cipher).to receive(:method_defined?).with(:auth_data=).and_return(true) # OpenSSL without AEAD support - OpenSSL::Cipher.should_receive(:ciphers).and_return([]) - lambda { encryptor }.should raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) + expect(OpenSSL::Cipher).to receive(:ciphers).and_return([]) + expect { encryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) end context "on platforms with old Ruby", :ruby_lt_20 do it "throws an error warning about the Ruby version" do - lambda { encryptor }.should raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires Ruby/) + expect { encryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires Ruby/) end end # context on platforms with old Ruby @@ -151,7 +151,7 @@ describe Chef::EncryptedDataBagItem::Encryptor do context "on platforms with old OpenSSL", :openssl_lt_101 do it "throws an error warning about the OpenSSL version" do - lambda { encryptor }.should raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) + expect { encryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) end end # context on platforms with old OpenSSL @@ -172,11 +172,11 @@ describe Chef::EncryptedDataBagItem::Decryptor do shared_examples "decryption examples" do it "decrypts the encrypted value" do - decryptor.decrypted_data.should eq(json_wrapped_data) + expect(decryptor.decrypted_data).to eq(json_wrapped_data) end it "unwraps the encrypted data and returns it" do - decryptor.for_decrypted_item.should eq plaintext_data + expect(decryptor.for_decrypted_item).to eq plaintext_data end end @@ -194,12 +194,12 @@ describe Chef::EncryptedDataBagItem::Decryptor do it "rejects the data if the authentication tag is wrong" do encrypted_value["auth_tag"] = bogus_auth_tag - lambda { decryptor.for_decrypted_item }.should raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) + expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end it "rejects the data if the authentication tag is missing" do encrypted_value.delete("auth_tag") - lambda { decryptor.for_decrypted_item }.should raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) + expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end end # context on supported platforms @@ -217,7 +217,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do context "on platforms with old Ruby", :ruby_lt_20 do it "throws an error warning about the Ruby version" do - lambda { decryptor }.should raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires Ruby/) + expect { decryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires Ruby/) end end # context on platforms with old Ruby @@ -225,7 +225,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do context "on platforms with old OpenSSL", :openssl_lt_101 do it "throws an error warning about the OpenSSL version" do - lambda { decryptor }.should raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) + expect { decryptor }.to raise_error(Chef::EncryptedDataBagItem::EncryptedDataBagRequirementsFailure, /requires an OpenSSL/) end end # context on unsupported platforms @@ -249,12 +249,12 @@ describe Chef::EncryptedDataBagItem::Decryptor do it "rejects the data if the hmac is wrong" do encrypted_value["hmac"] = bogus_hmac - lambda { decryptor.for_decrypted_item }.should raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) + expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end it "rejects the data if the hmac is missing" do encrypted_value.delete("hmac") - lambda { decryptor.for_decrypted_item }.should raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) + expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end end @@ -266,7 +266,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do end it "selects the correct strategy for version 1" do - decryptor.should be_a_instance_of Chef::EncryptedDataBagItem::Decryptor::Version1Decryptor + expect(decryptor).to be_a_instance_of Chef::EncryptedDataBagItem::Decryptor::Version1Decryptor end include_examples "decryption examples" @@ -276,8 +276,8 @@ describe Chef::EncryptedDataBagItem::Decryptor do # Over a large number of tests on a variety of systems, we occasionally # see the decryption step "succeed" but return invalid data (e.g., not # the original plain text) [CHEF-3858] - decryptor.should_receive(:decrypted_data).and_return("lksajdf") - lambda { decryptor.for_decrypted_item }.should raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) + expect(decryptor).to receive(:decrypted_data).and_return("lksajdf") + expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end end @@ -285,7 +285,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do let(:decryption_key) { "wrong-passwd" } it "raises a sensible error" do - lambda { decryptor.for_decrypted_item }.should raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) + expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::DecryptionFailure) end end @@ -297,7 +297,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do end it "raises a sensible error" do - lambda { decryptor.for_decrypted_item }.should raise_error(Chef::EncryptedDataBagItem::UnsupportedCipher) + expect { decryptor.for_decrypted_item }.to raise_error(Chef::EncryptedDataBagItem::UnsupportedCipher) end end @@ -307,7 +307,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do end it "raises an error attempting to decrypt" do - lambda { decryptor }.should raise_error(Chef::EncryptedDataBagItem::UnacceptableEncryptedDataBagItemFormat) + expect { decryptor }.to raise_error(Chef::EncryptedDataBagItem::UnacceptableEncryptedDataBagItemFormat) end end @@ -320,11 +320,11 @@ describe Chef::EncryptedDataBagItem::Decryptor do end it "selects the correct strategy for version 0" do - decryptor.should be_a_instance_of(Chef::EncryptedDataBagItem::Decryptor::Version0Decryptor) + expect(decryptor).to be_a_instance_of(Chef::EncryptedDataBagItem::Decryptor::Version0Decryptor) end it "decrypts the encrypted value" do - decryptor.for_decrypted_item.should eq plaintext_data + expect(decryptor.for_decrypted_item).to eq plaintext_data end context "and version 1 format is required" do @@ -333,7 +333,7 @@ describe Chef::EncryptedDataBagItem::Decryptor do end it "raises an error attempting to decrypt" do - lambda { decryptor }.should raise_error(Chef::EncryptedDataBagItem::UnacceptableEncryptedDataBagItemFormat) + expect { decryptor }.to raise_error(Chef::EncryptedDataBagItem::UnacceptableEncryptedDataBagItemFormat) end end @@ -355,27 +355,27 @@ describe Chef::EncryptedDataBagItem do describe "encrypting" do it "doesn't encrypt the 'id' key" do - encoded_data["id"].should eq "item_name" + expect(encoded_data["id"]).to eq "item_name" end it "encrypts non-collection objects" do - encoded_data["greeting"]["version"].should eq 1 - encoded_data["greeting"].should have_key("iv") + expect(encoded_data["greeting"]["version"]).to eq 1 + expect(encoded_data["greeting"]).to have_key("iv") iv = encoded_data["greeting"]["iv"] encryptor = Chef::EncryptedDataBagItem::Encryptor.new("hello", secret, iv) - encoded_data["greeting"]["encrypted_data"].should eq(encryptor.for_encrypted_item["encrypted_data"]) + expect(encoded_data["greeting"]["encrypted_data"]).to eq(encryptor.for_encrypted_item["encrypted_data"]) end it "encrypts nested values" do - encoded_data["nested"]["version"].should eq 1 - encoded_data["nested"].should have_key("iv") + expect(encoded_data["nested"]["version"]).to eq 1 + expect(encoded_data["nested"]).to have_key("iv") iv = encoded_data["nested"]["iv"] encryptor = Chef::EncryptedDataBagItem::Encryptor.new(plaintext_data["nested"], secret, iv) - encoded_data["nested"]["encrypted_data"].should eq(encryptor.for_encrypted_item["encrypted_data"]) + expect(encoded_data["nested"]["encrypted_data"]).to eq(encryptor.for_encrypted_item["encrypted_data"]) end end @@ -383,31 +383,31 @@ describe Chef::EncryptedDataBagItem do describe "decrypting" do it "doesn't try to decrypt 'id'" do - encrypted_data_bag_item["id"].should eq(plaintext_data["id"]) + expect(encrypted_data_bag_item["id"]).to eq(plaintext_data["id"]) end it "decrypts 'greeting'" do - encrypted_data_bag_item["greeting"].should eq(plaintext_data["greeting"]) + expect(encrypted_data_bag_item["greeting"]).to eq(plaintext_data["greeting"]) end it "decrypts 'nested'" do - encrypted_data_bag_item["nested"].should eq(plaintext_data["nested"]) + expect(encrypted_data_bag_item["nested"]).to eq(plaintext_data["nested"]) end it "decrypts everyting via to_hash" do - encrypted_data_bag_item.to_hash.should eq(plaintext_data) + expect(encrypted_data_bag_item.to_hash).to eq(plaintext_data) end it "handles missing keys gracefully" do - encrypted_data_bag_item["no-such-key"].should be_nil + expect(encrypted_data_bag_item["no-such-key"]).to be_nil end end describe "loading" do it "should defer to Chef::DataBagItem.load" do - Chef::DataBagItem.stub(:load).with(:the_bag, "my_codes").and_return(encoded_data) + allow(Chef::DataBagItem).to receive(:load).with(:the_bag, "my_codes").and_return(encoded_data) edbi = Chef::EncryptedDataBagItem.load(:the_bag, "my_codes", secret) - edbi["greeting"].should eq(plaintext_data["greeting"]) + expect(edbi["greeting"]).to eq(plaintext_data["greeting"]) end end @@ -416,45 +416,45 @@ describe Chef::EncryptedDataBagItem do context "when /var/mysecret exists" do before do - ::File.stub(:exist?).with("/var/mysecret").and_return(true) - IO.stub(:read).with("/var/mysecret").and_return(secret) + allow(::File).to receive(:exist?).with("/var/mysecret").and_return(true) + allow(IO).to receive(:read).with("/var/mysecret").and_return(secret) end it "load_secret('/var/mysecret') reads the secret" do - Chef::EncryptedDataBagItem.load_secret("/var/mysecret").should eq secret + expect(Chef::EncryptedDataBagItem.load_secret("/var/mysecret")).to eq secret end end context "when /etc/chef/encrypted_data_bag_secret exists" do before do path = Chef::Config.platform_specific_path("/etc/chef/encrypted_data_bag_secret") - ::File.stub(:exist?).with(path).and_return(true) - IO.stub(:read).with(path).and_return(secret) + allow(::File).to receive(:exist?).with(path).and_return(true) + allow(IO).to receive(:read).with(path).and_return(secret) end it "load_secret(nil) reads the secret" do - Chef::EncryptedDataBagItem.load_secret(nil).should eq secret + expect(Chef::EncryptedDataBagItem.load_secret(nil)).to eq secret end end context "when /etc/chef/encrypted_data_bag_secret does not exist" do before do path = Chef::Config.platform_specific_path("/etc/chef/encrypted_data_bag_secret") - ::File.stub(:exist?).with(path).and_return(false) + allow(::File).to receive(:exist?).with(path).and_return(false) end it "load_secret(nil) emits a reasonable error message" do - lambda { Chef::EncryptedDataBagItem.load_secret(nil) }.should raise_error(ArgumentError, /No secret specified and no secret found at #{Chef::Config[:encrypted_data_bag_secret]}/) + expect { Chef::EncryptedDataBagItem.load_secret(nil) }.to raise_error(ArgumentError, /No secret specified and no secret found at #{Chef::Config[:encrypted_data_bag_secret]}/) end end context "path argument is a URL" do before do - Kernel.stub(:open).with("http://www.opscode.com/").and_return(StringIO.new(secret)) + allow(Kernel).to receive(:open).with("http://www.opscode.com/").and_return(StringIO.new(secret)) end it "reads from the URL" do - Chef::EncryptedDataBagItem.load_secret("http://www.opscode.com/").should eq secret + expect(Chef::EncryptedDataBagItem.load_secret("http://www.opscode.com/")).to eq secret end end end diff --git a/spec/unit/environment_spec.rb b/spec/unit/environment_spec.rb index ffb8fbfeaf..ee3b8b21e1 100644 --- a/spec/unit/environment_spec.rb +++ b/spec/unit/environment_spec.rb @@ -29,75 +29,75 @@ describe Chef::Environment do describe "initialize" do it "should be a Chef::Environment" do - @environment.should be_a_kind_of(Chef::Environment) + expect(@environment).to be_a_kind_of(Chef::Environment) end end describe "name" do it "should let you set the name to a string" do - @environment.name("production").should == "production" + expect(@environment.name("production")).to eq("production") end it "should return the current name" do @environment.name("production") - @environment.name.should == "production" + expect(@environment.name).to eq("production") end it "should not accept spaces" do - lambda { @environment.name("production environment") }.should raise_error(ArgumentError) + expect { @environment.name("production environment") }.to raise_error(ArgumentError) end it "should not accept anything but strings" do - lambda { @environment.name(Array.new) }.should raise_error(ArgumentError) - lambda { @environment.name(Hash.new) }.should raise_error(ArgumentError) - lambda { @environment.name(2) }.should raise_error(ArgumentError) + expect { @environment.name(Array.new) }.to raise_error(ArgumentError) + expect { @environment.name(Hash.new) }.to raise_error(ArgumentError) + expect { @environment.name(2) }.to raise_error(ArgumentError) end end describe "description" do it "should let you set the description to a string" do - @environment.description("this is my test environment").should == "this is my test environment" + expect(@environment.description("this is my test environment")).to eq("this is my test environment") end it "should return the correct description" do @environment.description("I like running tests") - @environment.description.should == "I like running tests" + expect(@environment.description).to eq("I like running tests") end it "should not accept anything but strings" do - lambda { @environment.description(Array.new) }.should raise_error(ArgumentError) - lambda { @environment.description(Hash.new) }.should raise_error(ArgumentError) - lambda { @environment.description(42) }.should raise_error(ArgumentError) + expect { @environment.description(Array.new) }.to raise_error(ArgumentError) + expect { @environment.description(Hash.new) }.to raise_error(ArgumentError) + expect { @environment.description(42) }.to raise_error(ArgumentError) end end describe "default attributes" do it "should let you set the attributes hash explicitly" do - @environment.default_attributes({ :one => 'two' }).should == { :one => 'two' } + expect(@environment.default_attributes({ :one => 'two' })).to eq({ :one => 'two' }) end it "should let you return the attributes hash" do @environment.default_attributes({ :one => 'two' }) - @environment.default_attributes.should == { :one => 'two' } + expect(@environment.default_attributes).to eq({ :one => 'two' }) end it "should throw an ArgumentError if we aren't a kind of hash" do - lambda { @environment.default_attributes(Array.new) }.should raise_error(ArgumentError) + expect { @environment.default_attributes(Array.new) }.to raise_error(ArgumentError) end end describe "override attributes" do it "should let you set the attributes hash explicitly" do - @environment.override_attributes({ :one => 'two' }).should == { :one => 'two' } + expect(@environment.override_attributes({ :one => 'two' })).to eq({ :one => 'two' }) end it "should let you return the attributes hash" do @environment.override_attributes({ :one => 'two' }) - @environment.override_attributes.should == { :one => 'two' } + expect(@environment.override_attributes).to eq({ :one => 'two' }) end it "should throw an ArgumentError if we aren't a kind of hash" do - lambda { @environment.override_attributes(Array.new) }.should raise_error(ArgumentError) + expect { @environment.override_attributes(Array.new) }.to raise_error(ArgumentError) end end @@ -111,22 +111,22 @@ describe Chef::Environment do end it "should let you set the cookbook versions in a hash" do - @environment.cookbook_versions(@cookbook_versions).should == @cookbook_versions + expect(@environment.cookbook_versions(@cookbook_versions)).to eq(@cookbook_versions) end it "should return the cookbook versions" do @environment.cookbook_versions(@cookbook_versions) - @environment.cookbook_versions.should == @cookbook_versions + expect(@environment.cookbook_versions).to eq(@cookbook_versions) end it "should not accept anything but a hash" do - lambda { @environment.cookbook_versions("I am a string!") }.should raise_error(ArgumentError) - lambda { @environment.cookbook_versions(Array.new) }.should raise_error(ArgumentError) - lambda { @environment.cookbook_versions(42) }.should raise_error(ArgumentError) + expect { @environment.cookbook_versions("I am a string!") }.to raise_error(ArgumentError) + expect { @environment.cookbook_versions(Array.new) }.to raise_error(ArgumentError) + expect { @environment.cookbook_versions(42) }.to raise_error(ArgumentError) end it "should validate the hash" do - Chef::Environment.should_receive(:validate_cookbook_versions).with(@cookbook_versions).and_return true + expect(Chef::Environment).to receive(:validate_cookbook_versions).with(@cookbook_versions).and_return true @environment.cookbook_versions(@cookbook_versions) end end @@ -134,11 +134,11 @@ describe Chef::Environment do describe "cookbook" do it "should set the version of the cookbook in the cookbook_versions hash" do @environment.cookbook("apt", "~> 1.2.3") - @environment.cookbook_versions["apt"].should == "~> 1.2.3" + expect(@environment.cookbook_versions["apt"]).to eq("~> 1.2.3") end it "should validate the cookbook version it is passed" do - Chef::Environment.should_receive(:validate_cookbook_version).with(">= 1.2.3").and_return true + expect(Chef::Environment).to receive(:validate_cookbook_version).with(">= 1.2.3").and_return true @environment.cookbook("apt", ">= 1.2.3") end end @@ -157,9 +157,9 @@ describe Chef::Environment do it "should update everything but name" do @environment.update_from!(@example) - @environment.name.should == "prod" - @environment.description.should == @example.description - @environment.cookbook_versions.should == @example.cookbook_versions + expect(@environment.name).to eq("prod") + expect(@environment.description).to eq(@example.description) + expect(@environment.cookbook_versions).to eq(@example.cookbook_versions) end end @@ -173,16 +173,16 @@ describe Chef::Environment do %w{name description cookbook_versions}.each do |t| it "should include '#{t}'" do - @hash[t].should == @environment.send(t.to_sym) + expect(@hash[t]).to eq(@environment.send(t.to_sym)) end end it "should include 'json_class'" do - @hash["json_class"].should == "Chef::Environment" + expect(@hash["json_class"]).to eq("Chef::Environment") end it "should include 'chef_type'" do - @hash["chef_type"].should == "environment" + expect(@hash["chef_type"]).to eq("environment") end end @@ -196,16 +196,16 @@ describe Chef::Environment do %w{name description cookbook_versions}.each do |t| it "should include '#{t}'" do - @json.should =~ /"#{t}":#{Regexp.escape(Chef::JSONCompat.to_json(@environment.send(t.to_sym)))}/ + expect(@json).to match(/"#{t}":#{Regexp.escape(Chef::JSONCompat.to_json(@environment.send(t.to_sym)))}/) end end it "should include 'json_class'" do - @json.should =~ /"json_class":"Chef::Environment"/ + expect(@json).to match(/"json_class":"Chef::Environment"/) end it "should include 'chef_type'" do - @json.should =~ /"chef_type":"environment"/ + expect(@json).to match(/"chef_type":"environment"/) end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -230,12 +230,12 @@ describe Chef::Environment do end it "should return a Chef::Environment" do - @environment.should be_a_kind_of(Chef::Environment) + expect(@environment).to be_a_kind_of(Chef::Environment) end %w{name description cookbook_versions}.each do |t| it "should match '#{t}'" do - @environment.send(t.to_sym).should == @data[t] + expect(@environment.send(t.to_sym)).to eq(@data[t]) end end end @@ -251,39 +251,39 @@ describe Chef::Environment do it "should validate the version string of each cookbook" do @cookbook_versions.each do |cookbook, version| - Chef::Environment.should_receive(:validate_cookbook_version).with(version).and_return true + expect(Chef::Environment).to receive(:validate_cookbook_version).with(version).and_return true end Chef::Environment.validate_cookbook_versions(@cookbook_versions) end it "should return false if anything other than a hash is passed as the argument" do - Chef::Environment.validate_cookbook_versions(Array.new).should == false - Chef::Environment.validate_cookbook_versions(42).should == false - Chef::Environment.validate_cookbook_versions(Chef::CookbookVersion.new("meta")).should == false - Chef::Environment.validate_cookbook_versions("cookbook => 1.2.3").should == false + expect(Chef::Environment.validate_cookbook_versions(Array.new)).to eq(false) + expect(Chef::Environment.validate_cookbook_versions(42)).to eq(false) + expect(Chef::Environment.validate_cookbook_versions(Chef::CookbookVersion.new("meta"))).to eq(false) + expect(Chef::Environment.validate_cookbook_versions("cookbook => 1.2.3")).to eq(false) end end describe "self.validate_cookbook_version" do it "should validate correct version numbers" do - Chef::Environment.validate_cookbook_version("= 1.2.3").should == true - Chef::Environment.validate_cookbook_version("=1.2.3").should == true - Chef::Environment.validate_cookbook_version(">= 0.0.3").should == true - Chef::Environment.validate_cookbook_version(">=0.0.3").should == true + expect(Chef::Environment.validate_cookbook_version("= 1.2.3")).to eq(true) + expect(Chef::Environment.validate_cookbook_version("=1.2.3")).to eq(true) + expect(Chef::Environment.validate_cookbook_version(">= 0.0.3")).to eq(true) + expect(Chef::Environment.validate_cookbook_version(">=0.0.3")).to eq(true) # A lone version is allowed, interpreted as implicit '=' - Chef::Environment.validate_cookbook_version("1.2.3").should == true + expect(Chef::Environment.validate_cookbook_version("1.2.3")).to eq(true) end it "should return false when an invalid version is given" do - Chef::Environment.validate_cookbook_version(Chef::CookbookVersion.new("meta")).should == false - Chef::Environment.validate_cookbook_version("= 1.2.3a").should == false - Chef::Environment.validate_cookbook_version("=1.2.3a").should == false - Chef::Environment.validate_cookbook_version("= 1").should == false - Chef::Environment.validate_cookbook_version("=1").should == false - Chef::Environment.validate_cookbook_version("= a").should == false - Chef::Environment.validate_cookbook_version("=a").should == false - Chef::Environment.validate_cookbook_version("= 1.2.3.4").should == false - Chef::Environment.validate_cookbook_version("=1.2.3.4").should == false + expect(Chef::Environment.validate_cookbook_version(Chef::CookbookVersion.new("meta"))).to eq(false) + expect(Chef::Environment.validate_cookbook_version("= 1.2.3a")).to eq(false) + expect(Chef::Environment.validate_cookbook_version("=1.2.3a")).to eq(false) + expect(Chef::Environment.validate_cookbook_version("= 1")).to eq(false) + expect(Chef::Environment.validate_cookbook_version("=1")).to eq(false) + expect(Chef::Environment.validate_cookbook_version("= a")).to eq(false) + expect(Chef::Environment.validate_cookbook_version("=a")).to eq(false) + expect(Chef::Environment.validate_cookbook_version("= 1.2.3.4")).to eq(false) + expect(Chef::Environment.validate_cookbook_version("=1.2.3.4")).to eq(false) end describe "in solo mode" do @@ -296,9 +296,9 @@ describe Chef::Environment do end it "should raise and exception" do - lambda { + expect { Chef::Environment.validate_cookbook_version("= 1.2.3.4") - }.should raise_error Chef::Exceptions::IllegalVersionConstraint, + }.to raise_error Chef::Exceptions::IllegalVersionConstraint, "Environment cookbook version constraints not allowed in chef-solo" end end @@ -312,17 +312,17 @@ describe Chef::Environment do it "updates the name from parameters[:name]" do @environment.update_from_params(:name => "kurrupt") - @environment.name.should == "kurrupt" + expect(@environment.name).to eq("kurrupt") end it "validates the name given in the params" do - @environment.update_from_params(:name => "@$%^&*()").should be_false - @environment.invalid_fields[:name].should == %q|Option name's value @$%^&*() does not match regular expression /^[\-[:alnum:]_]+$/| + expect(@environment.update_from_params(:name => "@$%^&*()")).to be_falsey + expect(@environment.invalid_fields[:name]).to eq(%q|Option name's value @$%^&*() does not match regular expression /^[\-[:alnum:]_]+$/|) end it "updates the description from parameters[:description]" do @environment.update_from_params(:description => "wow, writing your own object mapper is kinda painful") - @environment.description.should == "wow, writing your own object mapper is kinda painful" + expect(@environment.description).to eq("wow, writing your own object mapper is kinda painful") end it "updates cookbook version constraints from the hash in parameters[:cookbook_version_constraints]" do @@ -331,34 +331,34 @@ describe Chef::Environment do # the way merb does params params = {:name=>"superbowl", :cookbook_version => {"0" => "apache2 ~> 1.0.0", "1" => "nginx < 2.0.0"}} @environment.update_from_params(params) - @environment.cookbook_versions.should == {"apache2" => "~> 1.0.0", "nginx" => "< 2.0.0"} + expect(@environment.cookbook_versions).to eq({"apache2" => "~> 1.0.0", "nginx" => "< 2.0.0"}) end it "validates the cookbook constraints" do params = {:cookbook_version => {"0" => "apache2 >>> 1.0.0"}} - @environment.update_from_params(params).should be_false + expect(@environment.update_from_params(params)).to be_falsey err_msg = @environment.invalid_fields[:cookbook_version]["0"] - err_msg.should == "apache2 >>> 1.0.0 is not a valid cookbook constraint" + expect(err_msg).to eq("apache2 >>> 1.0.0 is not a valid cookbook constraint") end it "is not valid if the name is not present" do - @environment.validate_required_attrs_present.should be_false - @environment.invalid_fields[:name].should == "name cannot be empty" + expect(@environment.validate_required_attrs_present).to be_falsey + expect(@environment.invalid_fields[:name]).to eq("name cannot be empty") end it "is not valid after updating from params if the name is not present" do - @environment.update_from_params({}).should be_false - @environment.invalid_fields[:name].should == "name cannot be empty" + expect(@environment.update_from_params({})).to be_falsey + expect(@environment.invalid_fields[:name]).to eq("name cannot be empty") end it "updates default attributes from a JSON string in params[:attributes]" do @environment.update_from_params(:name => "fuuu", :default_attributes => %q|{"fuuu":"RAGE"}|) - @environment.default_attributes.should == {"fuuu" => "RAGE"} + expect(@environment.default_attributes).to eq({"fuuu" => "RAGE"}) end it "updates override attributes from a JSON string in params[:attributes]" do @environment.update_from_params(:name => "fuuu", :override_attributes => %q|{"foo":"override"}|) - @environment.override_attributes.should == {"foo" => "override"} + expect(@environment.override_attributes).to eq({"foo" => "override"}) end end @@ -366,25 +366,25 @@ describe Chef::Environment do describe "api model" do before(:each) do @rest = double("Chef::REST") - Chef::REST.stub(:new).and_return(@rest) + allow(Chef::REST).to receive(:new).and_return(@rest) @query = double("Chef::Search::Query") - Chef::Search::Query.stub(:new).and_return(@query) + allow(Chef::Search::Query).to receive(:new).and_return(@query) end describe "list" do describe "inflated" do it "should return a hash of environment names and objects" do e1 = double("Chef::Environment", :name => "one") - @query.should_receive(:search).with(:environment).and_yield(e1) + expect(@query).to receive(:search).with(:environment).and_yield(e1) r = Chef::Environment.list(true) - r["one"].should == e1 + expect(r["one"]).to eq(e1) end end it "should return a hash of environment names and urls" do - @rest.should_receive(:get_rest).and_return({ "one" => "http://foo" }) + expect(@rest).to receive(:get_rest).and_return({ "one" => "http://foo" }) r = Chef::Environment.list - r["one"].should == "http://foo" + expect(r["one"]).to eq("http://foo") end end end @@ -401,18 +401,18 @@ describe Chef::Environment do end it "should get the environment from the environment_path" do - File.should_receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) - File.should_receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(false) - File.should_receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).exactly(2).times.and_return(true) - File.should_receive(:readable?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(true) + expect(File).to receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) + expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(false) + expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).exactly(2).times.and_return(true) + expect(File).to receive(:readable?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(true) role_dsl="name \"foo\"\ndescription \"desc\"\n" - IO.should_receive(:read).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(role_dsl) + expect(IO).to receive(:read).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(role_dsl) Chef::Environment.load('foo') end it "should return a Chef::Environment object from JSON" do - File.should_receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) - File.should_receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(true) + expect(File).to receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) + expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(true) environment_hash = { "name" => "foo", "default_attributes" => { @@ -424,45 +424,45 @@ describe Chef::Environment do "description" => "desc", "chef_type" => "environment" } - IO.should_receive(:read).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(Chef::JSONCompat.to_json(environment_hash)) + expect(IO).to receive(:read).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(Chef::JSONCompat.to_json(environment_hash)) environment = Chef::Environment.load('foo') - environment.should be_a_kind_of(Chef::Environment) - environment.name.should == environment_hash['name'] - environment.description.should == environment_hash['description'] - environment.default_attributes.should == environment_hash['default_attributes'] + expect(environment).to be_a_kind_of(Chef::Environment) + expect(environment.name).to eq(environment_hash['name']) + expect(environment.description).to eq(environment_hash['description']) + expect(environment.default_attributes).to eq(environment_hash['default_attributes']) end it "should return a Chef::Environment object from Ruby DSL" do - File.should_receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) - File.should_receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(false) - File.should_receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).exactly(2).times.and_return(true) - File.should_receive(:readable?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(true) + expect(File).to receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) + expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(false) + expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).exactly(2).times.and_return(true) + expect(File).to receive(:readable?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(true) role_dsl="name \"foo\"\ndescription \"desc\"\n" - IO.should_receive(:read).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(role_dsl) + expect(IO).to receive(:read).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(role_dsl) environment = Chef::Environment.load('foo') - environment.should be_a_kind_of(Chef::Environment) - environment.name.should == 'foo' - environment.description.should == 'desc' + expect(environment).to be_a_kind_of(Chef::Environment) + expect(environment.name).to eq('foo') + expect(environment.description).to eq('desc') end it 'should raise an error if the configured environment_path is invalid' do - File.should_receive(:directory?).with(Chef::Config[:environment_path]).and_return(false) + expect(File).to receive(:directory?).with(Chef::Config[:environment_path]).and_return(false) - lambda { + expect { Chef::Environment.load('foo') - }.should raise_error Chef::Exceptions::InvalidEnvironmentPath, "Environment path '/var/chef/environments' is invalid" + }.to raise_error Chef::Exceptions::InvalidEnvironmentPath, "Environment path '/var/chef/environments' is invalid" end it 'should raise an error if the file does not exist' do - File.should_receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) - File.should_receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(false) - File.should_receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(false) + expect(File).to receive(:directory?).with(Chef::Config[:environment_path]).and_return(true) + expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.json')).and_return(false) + expect(File).to receive(:exists?).with(File.join(Chef::Config[:environment_path], 'foo.rb')).and_return(false) - lambda { + expect { Chef::Environment.load('foo') - }.should raise_error Chef::Exceptions::EnvironmentNotFound, "Environment 'foo' could not be loaded from disk" + }.to raise_error Chef::Exceptions::EnvironmentNotFound, "Environment 'foo' could not be loaded from disk" end end end diff --git a/spec/unit/exceptions_spec.rb b/spec/unit/exceptions_spec.rb index 21b0abb9bf..6318ec9227 100644 --- a/spec/unit/exceptions_spec.rb +++ b/spec/unit/exceptions_spec.rb @@ -72,7 +72,7 @@ describe Chef::Exceptions do exception_to_super_class.each do |exception, expected_super_class| it "should have an exception class of #{exception} which inherits from #{expected_super_class}" do - lambda{ raise exception }.should raise_error(expected_super_class) + expect{ raise exception }.to raise_error(expected_super_class) end if exception.methods.include?(:to_json) diff --git a/spec/unit/file_access_control_spec.rb b/spec/unit/file_access_control_spec.rb index 4e257c2a22..cd0bd55cc3 100644 --- a/spec/unit/file_access_control_spec.rb +++ b/spec/unit/file_access_control_spec.rb @@ -43,47 +43,47 @@ describe Chef::FileAccessControl do end it "has a resource" do - @fac.resource.should equal(@resource) + expect(@fac.resource).to equal(@resource) end it "has a file to manage" do - @fac.file.should == '/tmp/different_file.txt' + expect(@fac.file).to eq('/tmp/different_file.txt') end it "is not modified yet" do - @fac.should_not be_modified + expect(@fac).not_to be_modified end it "determines the uid of the owner specified by the resource" do - Etc.should_receive(:getpwnam).with('toor').and_return(OpenStruct.new(:uid => 2342)) - @fac.target_uid.should == 2342 + expect(Etc).to receive(:getpwnam).with('toor').and_return(OpenStruct.new(:uid => 2342)) + expect(@fac.target_uid).to eq(2342) end it "raises a Chef::Exceptions::UserIDNotFound error when Etc can't find the user's name" do - Etc.should_receive(:getpwnam).with('toor').and_raise(ArgumentError) - lambda { @fac.target_uid ; @provider_requirements.run(:create) }.should raise_error(Chef::Exceptions::UserIDNotFound, "cannot determine user id for 'toor', does the user exist on this system?") + expect(Etc).to receive(:getpwnam).with('toor').and_raise(ArgumentError) + expect { @fac.target_uid ; @provider_requirements.run(:create) }.to raise_error(Chef::Exceptions::UserIDNotFound, "cannot determine user id for 'toor', does the user exist on this system?") end it "does not attempt to resolve the uid if the user is not specified" do resource = Chef::Resource::File.new("a file") fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.target_uid.should be_nil + expect(fac.target_uid).to be_nil end it "does not want to update the owner if none is specified" do resource = Chef::Resource::File.new("a file") fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.should_update_owner?.should be_false + expect(fac.should_update_owner?).to be_falsey end it "raises an ArgumentError if the resource's owner is set to something wack" do @resource.instance_variable_set(:@owner, :diaf) - lambda { @fac.target_uid ; @provider_requirements.run(:create) }.should raise_error(ArgumentError) + expect { @fac.target_uid ; @provider_requirements.run(:create) }.to raise_error(ArgumentError) end it "uses the resource's uid for the target uid when the resource's owner is specified by an integer" do @resource.owner(2342) - @fac.target_uid.should == 2342 + expect(@fac.target_uid).to eq(2342) end it "wraps uids to their negative complements to correctly handle negative uids" do @@ -93,28 +93,28 @@ describe Chef::FileAccessControl do # uids. So we have to get ruby and negative uids to smoke the peace pipe # with each other. @resource.owner('nobody') - Etc.should_receive(:getpwnam).with('nobody').and_return(OpenStruct.new(:uid => (4294967294))) - @fac.target_uid.should == -2 + expect(Etc).to receive(:getpwnam).with('nobody').and_return(OpenStruct.new(:uid => (4294967294))) + expect(@fac.target_uid).to eq(-2) end it "does not wrap uids to their negative complements beyond -9" do # More: when OSX userIDs are created by ActiveDirectory sync, it tends to use huge numbers # which had been incorrectly wrapped. It does not look like the OSX IDs go below -2 @resource.owner('bigdude') - Etc.should_receive(:getpwnam).with('bigdude').and_return(OpenStruct.new(:uid => (4294967286))) - @fac.target_uid.should == 4294967286 + expect(Etc).to receive(:getpwnam).with('bigdude').and_return(OpenStruct.new(:uid => (4294967286))) + expect(@fac.target_uid).to eq(4294967286) end it "wants to update the owner when the current owner is nil (creating a file)" do @current_resource.owner(nil) @resource.owner(2342) - @fac.should_update_owner?.should be_true + expect(@fac.should_update_owner?).to be_truthy end it "wants to update the owner when the current owner doesn't match desired" do @current_resource.owner(3224) @resource.owner(2342) - @fac.should_update_owner?.should be_true + expect(@fac.should_update_owner?).to be_truthy end it "includes updating ownership in its list of desired changes" do @@ -122,72 +122,72 @@ describe Chef::FileAccessControl do resource.owner(2342) @current_resource.owner(100) fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.describe_changes.should == ["change owner from '100' to '2342'"] + expect(fac.describe_changes).to eq(["change owner from '100' to '2342'"]) end it "sets the file's owner as specified in the resource when the current owner is incorrect" do @resource.owner(2342) - File.should_receive(:chown).with(2342, nil, '/tmp/different_file.txt') + expect(File).to receive(:chown).with(2342, nil, '/tmp/different_file.txt') @fac.set_owner - @fac.should be_modified + expect(@fac).to be_modified end it "doesn't set the file's owner if it already matches" do @resource.owner(2342) @current_resource.owner(2342) - File.should_not_receive(:chown) + expect(File).not_to receive(:chown) @fac.set_owner - @fac.should_not be_modified + expect(@fac).not_to be_modified end it "doesn't want to update a file's owner when it's already correct" do @resource.owner(2342) @current_resource.owner(2342) - @fac.should_update_owner?.should be_false + expect(@fac.should_update_owner?).to be_falsey end it "determines the gid of the group specified by the resource" do - Etc.should_receive(:getgrnam).with('wheel').and_return(OpenStruct.new(:gid => 2342)) - @fac.target_gid.should == 2342 + expect(Etc).to receive(:getgrnam).with('wheel').and_return(OpenStruct.new(:gid => 2342)) + expect(@fac.target_gid).to eq(2342) end it "uses a user specified gid as the gid" do @resource.group(2342) - @fac.target_gid.should == 2342 + expect(@fac.target_gid).to eq(2342) end it "raises a Chef::Exceptions::GroupIDNotFound error when Etc can't find the user's name" do - Etc.should_receive(:getgrnam).with('wheel').and_raise(ArgumentError) - lambda { @fac.target_gid; @provider_requirements.run(:create) }.should raise_error(Chef::Exceptions::GroupIDNotFound, "cannot determine group id for 'wheel', does the group exist on this system?") + expect(Etc).to receive(:getgrnam).with('wheel').and_raise(ArgumentError) + expect { @fac.target_gid; @provider_requirements.run(:create) }.to raise_error(Chef::Exceptions::GroupIDNotFound, "cannot determine group id for 'wheel', does the group exist on this system?") end it "does not attempt to resolve a gid when none is supplied" do resource = Chef::Resource::File.new('crab') fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.target_gid.should be_nil + expect(fac.target_gid).to be_nil end it "does not want to update the group when no target group is specified" do resource = Chef::Resource::File.new('crab') fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.should_update_group?.should be_false + expect(fac.should_update_group?).to be_falsey end it "raises an error when the supplied group name is an alien" do @resource.instance_variable_set(:@group, :failburger) - lambda { @fac.target_gid; @provider_requirements.run(:create) }.should raise_error(ArgumentError) + expect { @fac.target_gid; @provider_requirements.run(:create) }.to raise_error(ArgumentError) end it "wants to update the group when the current group is nil (creating a file)" do @resource.group(2342) @current_resource.group(nil) - @fac.should_update_group?.should be_true + expect(@fac.should_update_group?).to be_truthy end it "wants to update the group when the current group doesn't match the target group" do @resource.group(2342) @current_resource.group(815) - @fac.should_update_group?.should be_true + expect(@fac.should_update_group?).to be_truthy end it "includes updating the group in the list of changes" do @@ -195,22 +195,22 @@ describe Chef::FileAccessControl do resource.group(2342) @current_resource.group(815) fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.describe_changes.should == ["change group from '815' to '2342'"] + expect(fac.describe_changes).to eq(["change group from '815' to '2342'"]) end it "sets the file's group as specified in the resource when the group is not correct" do @resource.group(2342) @current_resource.group(815) - File.should_receive(:chown).with(nil, 2342, '/tmp/different_file.txt') + expect(File).to receive(:chown).with(nil, 2342, '/tmp/different_file.txt') @fac.set_group - @fac.should be_modified + expect(@fac).to be_modified end it "doesn't want to modify the file's group when the current group is correct" do @resource.group(2342) @current_resource.group(2342) - @fac.should_update_group?.should be_false + expect(@fac.should_update_group?).to be_falsey end it "doesnt set the file's group if it is already correct" do @@ -218,43 +218,43 @@ describe Chef::FileAccessControl do @current_resource.group(2342) # @fac.stub(:stat).and_return(OpenStruct.new(:gid => 2342)) - File.should_not_receive(:chown) + expect(File).not_to receive(:chown) @fac.set_group - @fac.should_not be_modified + expect(@fac).not_to be_modified end it "uses the supplied mode as octal when it's a string" do @resource.mode('444') - @fac.target_mode.should == 292 # octal 444 => decimal 292 + expect(@fac.target_mode).to eq(292) # octal 444 => decimal 292 end it "uses the supplied mode verbatim when it's an integer" do @resource.mode(00444) - @fac.target_mode.should == 292 + expect(@fac.target_mode).to eq(292) end it "does not try to determine the mode when none is given" do resource = Chef::Resource::File.new('blahblah') fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.target_mode.should be_nil + expect(fac.target_mode).to be_nil end it "doesn't want to update the mode when no target mode is given" do resource = Chef::Resource::File.new('blahblah') fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.should_update_mode?.should be_false + expect(fac.should_update_mode?).to be_falsey end it "wants to update the mode when the current mode is nil (creating a file)" do @resource.mode("0400") @current_resource.mode(nil) - @fac.should_update_mode?.should be_true + expect(@fac.should_update_mode?).to be_truthy end it "wants to update the mode when the desired mode does not match the current mode" do @resource.mode("0400") @current_resource.mode("0644") - @fac.should_update_mode?.should be_true + expect(@fac.should_update_mode?).to be_truthy end it "includes changing the mode in the list of desired changes" do @@ -262,41 +262,41 @@ describe Chef::FileAccessControl do resource.mode("0750") @current_resource.mode("0444") fac = Chef::FileAccessControl.new(@current_resource, resource, @provider) - fac.describe_changes.should == ["change mode from '0444' to '0750'"] + expect(fac.describe_changes).to eq(["change mode from '0444' to '0750'"]) end it "sets the file's mode as specified in the resource when the current modes are incorrect" do # stat returns modes like 0100644 (octal) => 33188 (decimal) #@fac.stub(:stat).and_return(OpenStruct.new(:mode => 33188)) @current_resource.mode("0644") - File.should_receive(:chmod).with(256, '/tmp/different_file.txt') + expect(File).to receive(:chmod).with(256, '/tmp/different_file.txt') @fac.set_mode - @fac.should be_modified + expect(@fac).to be_modified end it "does not want to update the mode when the current mode is correct" do @current_resource.mode("0400") - @fac.should_update_mode?.should be_false + expect(@fac.should_update_mode?).to be_falsey end it "does not set the file's mode when the current modes are correct" do #@fac.stub(:stat).and_return(OpenStruct.new(:mode => 0100400)) @current_resource.mode("0400") - File.should_not_receive(:chmod) + expect(File).not_to receive(:chmod) @fac.set_mode - @fac.should_not be_modified + expect(@fac).not_to be_modified end it "sets all access controls on a file" do - @fac.stub(:stat).and_return(OpenStruct.new(:owner => 99, :group => 99, :mode => 0100444)) + allow(@fac).to receive(:stat).and_return(OpenStruct.new(:owner => 99, :group => 99, :mode => 0100444)) @resource.mode(0400) @resource.owner(0) @resource.group(0) - File.should_receive(:chmod).with(0400, '/tmp/different_file.txt') - File.should_receive(:chown).with(0, nil, '/tmp/different_file.txt') - File.should_receive(:chown).with(nil, 0, '/tmp/different_file.txt') + expect(File).to receive(:chmod).with(0400, '/tmp/different_file.txt') + expect(File).to receive(:chown).with(0, nil, '/tmp/different_file.txt') + expect(File).to receive(:chown).with(nil, 0, '/tmp/different_file.txt') @fac.set_all - @fac.should be_modified + expect(@fac).to be_modified end end end diff --git a/spec/unit/file_cache_spec.rb b/spec/unit/file_cache_spec.rb index f57f11dcc2..a24c3d3b97 100644 --- a/spec/unit/file_cache_spec.rb +++ b/spec/unit/file_cache_spec.rb @@ -32,11 +32,11 @@ describe Chef::FileCache do describe "when the relative path to the cache file doesn't exist" do it "creates intermediate directories as needed" do Chef::FileCache.store("whiz/bang", "I found a poop") - File.should exist(File.join(@file_cache_path, 'whiz')) + expect(File).to exist(File.join(@file_cache_path, 'whiz')) end it "creates the cached file at the correct relative path" do - File.should_receive(:open).with(File.join(@file_cache_path, 'whiz', 'bang'), "w",416).and_yield(@io) + expect(File).to receive(:open).with(File.join(@file_cache_path, 'whiz', 'bang'), "w",416).and_yield(@io) Chef::FileCache.store("whiz/bang", "borkborkbork") end @@ -44,12 +44,12 @@ describe Chef::FileCache do describe "when storing a file" do before do - File.stub(:open).and_yield(@io) + allow(File).to receive(:open).and_yield(@io) end it "should print the contents to the file" do Chef::FileCache.store("whiz/bang", "borkborkbork") - @io.string.should == "borkborkbork" + expect(@io.string).to eq("borkborkbork") end end @@ -58,11 +58,11 @@ describe Chef::FileCache do it "finds and reads the cached file" do FileUtils.mkdir_p(File.join(@file_cache_path, 'whiz')) File.open(File.join(@file_cache_path, 'whiz', 'bang'), 'w') { |f| f.print("borkborkbork") } - Chef::FileCache.load('whiz/bang').should == 'borkborkbork' + expect(Chef::FileCache.load('whiz/bang')).to eq('borkborkbork') end it "should raise a Chef::Exceptions::FileNotFound if the file doesn't exist" do - lambda { Chef::FileCache.load('whiz/bang') }.should raise_error(Chef::Exceptions::FileNotFound) + expect { Chef::FileCache.load('whiz/bang') }.to raise_error(Chef::Exceptions::FileNotFound) end end @@ -74,7 +74,7 @@ describe Chef::FileCache do it "unlinks the file" do Chef::FileCache.delete("whiz/bang") - File.should_not exist(File.join(@file_cache_path, 'whiz', 'bang')) + expect(File).not_to exist(File.join(@file_cache_path, 'whiz', 'bang')) end end @@ -88,11 +88,11 @@ describe Chef::FileCache do end it "should return the relative paths" do - Chef::FileCache.list.sort.should == %w{snappy/patter whiz/bang} + expect(Chef::FileCache.list.sort).to eq(%w{snappy/patter whiz/bang}) end it "searches for cached files by globbing" do - Chef::FileCache.find('snappy/**/*').should == %w{snappy/patter} + expect(Chef::FileCache.find('snappy/**/*')).to eq(%w{snappy/patter}) end end @@ -104,11 +104,11 @@ describe Chef::FileCache do it "has a key if the corresponding cache file exists" do FileUtils.touch(File.join(@file_cache_path, 'whiz', 'bang')) - Chef::FileCache.should have_key("whiz/bang") + expect(Chef::FileCache).to have_key("whiz/bang") end it "doesn't have a key if the corresponding cache file doesn't exist" do - Chef::FileCache.should_not have_key("whiz/bang") + expect(Chef::FileCache).not_to have_key("whiz/bang") end end end diff --git a/spec/unit/file_content_management/deploy/cp_spec.rb b/spec/unit/file_content_management/deploy/cp_spec.rb index dacf39295c..5c6583e8a6 100644 --- a/spec/unit/file_content_management/deploy/cp_spec.rb +++ b/spec/unit/file_content_management/deploy/cp_spec.rb @@ -26,7 +26,7 @@ describe Chef::FileContentManagement::Deploy::Cp do describe "creating the file" do it "touches the file to create it" do - FileUtils.should_receive(:touch).with(target_file_path) + expect(FileUtils).to receive(:touch).with(target_file_path) content_deployer.create(target_file_path) end end @@ -36,7 +36,7 @@ describe Chef::FileContentManagement::Deploy::Cp do let(:staging_file_path) { "/tmp/random-dir/staging-file.tmp" } it "copies the staging file's content" do - FileUtils.should_receive(:cp).with(staging_file_path, target_file_path) + expect(FileUtils).to receive(:cp).with(staging_file_path, target_file_path) content_deployer.deploy(staging_file_path, target_file_path) end diff --git a/spec/unit/file_content_management/deploy/mv_unix_spec.rb b/spec/unit/file_content_management/deploy/mv_unix_spec.rb index 0e8662b8ec..4511f91180 100644 --- a/spec/unit/file_content_management/deploy/mv_unix_spec.rb +++ b/spec/unit/file_content_management/deploy/mv_unix_spec.rb @@ -26,7 +26,7 @@ describe Chef::FileContentManagement::Deploy::MvUnix do describe "creating the file" do it "touches the file to create it" do - FileUtils.should_receive(:touch).with(target_file_path) + expect(FileUtils).to receive(:touch).with(target_file_path) content_deployer.create(target_file_path) end end @@ -44,9 +44,9 @@ describe Chef::FileContentManagement::Deploy::MvUnix do end before do - File.should_receive(:stat).with(target_file_path).and_return(target_file_stat) - File.should_receive(:chmod).with(target_file_mode, staging_file_path).and_return(1) - FileUtils.should_receive(:mv).with(staging_file_path, target_file_path) + expect(File).to receive(:stat).with(target_file_path).and_return(target_file_stat) + expect(File).to receive(:chmod).with(target_file_mode, staging_file_path).and_return(1) + expect(FileUtils).to receive(:mv).with(staging_file_path, target_file_path) end # This context represents the case where: @@ -63,8 +63,8 @@ describe Chef::FileContentManagement::Deploy::MvUnix do let(:target_file_gid) { 1001 } before do - File.should_receive(:chown).with(target_file_uid, nil, staging_file_path).and_return(1) - File.should_receive(:chown).with(nil, target_file_gid, staging_file_path).and_return(1) + expect(File).to receive(:chown).with(target_file_uid, nil, staging_file_path).and_return(1) + expect(File).to receive(:chown).with(nil, target_file_gid, staging_file_path).and_return(1) end it "fixes up permissions and moves the file into place" do @@ -85,11 +85,11 @@ describe Chef::FileContentManagement::Deploy::MvUnix do let(:target_file_gid) { 20 } before do - File.should_receive(:chown).with(target_file_uid, nil, staging_file_path).and_raise(Errno::EPERM) - File.should_receive(:chown).with(nil, target_file_gid, staging_file_path).and_raise(Errno::EPERM) + expect(File).to receive(:chown).with(target_file_uid, nil, staging_file_path).and_raise(Errno::EPERM) + expect(File).to receive(:chown).with(nil, target_file_gid, staging_file_path).and_raise(Errno::EPERM) - Chef::Log.should_receive(:warn).with(/^Could not set uid/) - Chef::Log.should_receive(:warn).with(/^Could not set gid/) + expect(Chef::Log).to receive(:warn).with(/^Could not set uid/) + expect(Chef::Log).to receive(:warn).with(/^Could not set gid/) end it "fixes up permissions and moves the file into place" do diff --git a/spec/unit/file_content_management/deploy/mv_windows_spec.rb b/spec/unit/file_content_management/deploy/mv_windows_spec.rb index 7c2a2d7e71..c52001cd26 100644 --- a/spec/unit/file_content_management/deploy/mv_windows_spec.rb +++ b/spec/unit/file_content_management/deploy/mv_windows_spec.rb @@ -41,7 +41,7 @@ describe Chef::FileContentManagement::Deploy::MvWindows do describe "creating the file" do it "touches the file to create it" do - FileUtils.should_receive(:touch).with(target_file_path) + expect(FileUtils).to receive(:touch).with(target_file_path) content_deployer.create(target_file_path) end end @@ -59,8 +59,8 @@ describe Chef::FileContentManagement::Deploy::MvWindows do end before do - Chef::ReservedNames::Win32::Security::SecurableObject. - stub(:new). + allow(Chef::ReservedNames::Win32::Security::SecurableObject). + to receive(:new). with(target_file_path). and_return(target_file_security_object, updated_target_security_object) @@ -68,11 +68,11 @@ describe Chef::FileContentManagement::Deploy::MvWindows do context "when run without adminstrator privileges" do before do - target_file_security_object.should_receive(:security_descriptor).and_raise(Chef::Exceptions::Win32APIError) + expect(target_file_security_object).to receive(:security_descriptor).and_raise(Chef::Exceptions::Win32APIError) end it "errors out with a WindowsNotAdmin error" do - lambda { content_deployer.deploy(staging_file_path, target_file_path)}.should raise_error(Chef::Exceptions::WindowsNotAdmin) + expect { content_deployer.deploy(staging_file_path, target_file_path)}.to raise_error(Chef::Exceptions::WindowsNotAdmin) end end @@ -94,19 +94,19 @@ describe Chef::FileContentManagement::Deploy::MvWindows do before do - target_file_security_object.stub(:security_descriptor).and_return(target_file_security_descriptor) + allow(target_file_security_object).to receive(:security_descriptor).and_return(target_file_security_descriptor) - FileUtils.should_receive(:mv).with(staging_file_path, target_file_path) + expect(FileUtils).to receive(:mv).with(staging_file_path, target_file_path) - updated_target_security_object.should_receive(:group=).with(original_target_file_group) - updated_target_security_object.should_receive(:owner=).with(original_target_file_owner) + expect(updated_target_security_object).to receive(:group=).with(original_target_file_group) + expect(updated_target_security_object).to receive(:owner=).with(original_target_file_owner) end context "and the target file has no dacl or sacl" do before do - target_file_security_descriptor.stub(:dacl_present?).and_return(false) - target_file_security_descriptor.stub(:sacl_present?).and_return(false) + allow(target_file_security_descriptor).to receive(:dacl_present?).and_return(false) + allow(target_file_security_descriptor).to receive(:sacl_present?).and_return(false) end it "fixes up permissions and moves the file into place" do @@ -129,26 +129,26 @@ describe Chef::FileContentManagement::Deploy::MvWindows do let(:custom_sacl) { double("Windows ACL for non-inherited sacl aces") } before do - target_file_security_descriptor.stub(:dacl_present?).and_return(true) - target_file_security_descriptor.stub(:dacl_inherits?).and_return(dacl_inherits?) + allow(target_file_security_descriptor).to receive(:dacl_present?).and_return(true) + allow(target_file_security_descriptor).to receive(:dacl_inherits?).and_return(dacl_inherits?) - target_file_security_descriptor.stub(:dacl).and_return(original_target_file_dacl) - Chef::ReservedNames::Win32::Security::ACL. - should_receive(:create). + allow(target_file_security_descriptor).to receive(:dacl).and_return(original_target_file_dacl) + expect(Chef::ReservedNames::Win32::Security::ACL). + to receive(:create). with([not_inherited_dacl_ace]). and_return(custom_dacl) - target_file_security_descriptor.stub(:sacl_present?).and_return(true) - target_file_security_descriptor.stub(:sacl_inherits?).and_return(sacl_inherits?) + allow(target_file_security_descriptor).to receive(:sacl_present?).and_return(true) + allow(target_file_security_descriptor).to receive(:sacl_inherits?).and_return(sacl_inherits?) - target_file_security_descriptor.stub(:sacl).and_return(original_target_file_sacl) - Chef::ReservedNames::Win32::Security::ACL. - should_receive(:create). + allow(target_file_security_descriptor).to receive(:sacl).and_return(original_target_file_sacl) + expect(Chef::ReservedNames::Win32::Security::ACL). + to receive(:create). with([not_inherited_sacl_ace]). and_return(custom_sacl) - updated_target_security_object.should_receive(:set_dacl).with(custom_dacl, dacl_inherits?) - updated_target_security_object.should_receive(:set_sacl).with(custom_sacl, sacl_inherits?) + expect(updated_target_security_object).to receive(:set_dacl).with(custom_dacl, dacl_inherits?) + expect(updated_target_security_object).to receive(:set_sacl).with(custom_sacl, sacl_inherits?) end context "and the dacl and sacl don't inherit" do diff --git a/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb index 95911689e4..ac19e91922 100644 --- a/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb @@ -51,7 +51,7 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do # Error inspector originally used file_cache_path which is incorrect on # chef-solo. Using cookbook_path should do the right thing for client and # solo. - Chef::Config.stub(:cookbook_path).and_return([ "/home/someuser/dev-laptop/cookbooks" ]) + allow(Chef::Config).to receive(:cookbook_path).and_return([ "/home/someuser/dev-laptop/cookbooks" ]) @trace = [ "/home/someuser/dev-laptop/cookbooks/syntax-err/recipes/default.rb:14:in `from_file'", "/home/someuser/dev-laptop/cookbooks/syntax-err/recipes/default.rb:11:in `from_file'", @@ -65,15 +65,15 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do "/home/someuser/dev-laptop/cookbooks/syntax-err/recipes/default.rb:14:in `from_file'", "/home/someuser/dev-laptop/cookbooks/syntax-err/recipes/default.rb:11:in `from_file'", ] - @inspector.filtered_bt.should == @expected_filtered_trace + expect(@inspector.filtered_bt).to eq(@expected_filtered_trace) end end describe "when explaining an error in the compile phase" do before do - Chef::Config.stub(:cookbook_path).and_return([ "/var/chef/cache/cookbooks" ]) + allow(Chef::Config).to receive(:cookbook_path).and_return([ "/var/chef/cache/cookbooks" ]) recipe_lines = BAD_RECIPE.split("\n").map {|l| l << "\n" } - IO.should_receive(:readlines).with("/var/chef/cache/cookbooks/syntax-err/recipes/default.rb").and_return(recipe_lines) + expect(IO).to receive(:readlines).with("/var/chef/cache/cookbooks/syntax-err/recipes/default.rb").and_return(recipe_lines) @trace = [ "/var/chef/cache/cookbooks/syntax-err/recipes/default.rb:14:in `from_file'", "/var/chef/cache/cookbooks/syntax-err/recipes/default.rb:11:in `from_file'", @@ -86,7 +86,7 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do end it "finds the line number of the error from the stacktrace" do - @inspector.culprit_line.should == 14 + expect(@inspector.culprit_line).to eq(14) end it "prints a pretty message" do @@ -96,9 +96,9 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do describe "when explaining an error on windows" do before do - Chef::Config.stub(:cookbook_path).and_return([ "C:/opscode/chef/var/cache/cookbooks" ]) + allow(Chef::Config).to receive(:cookbook_path).and_return([ "C:/opscode/chef/var/cache/cookbooks" ]) recipe_lines = BAD_RECIPE.split("\n").map {|l| l << "\n" } - IO.should_receive(:readlines).at_least(1).times.with(/:\/opscode\/chef\/var\/cache\/cookbooks\/foo\/recipes\/default.rb/).and_return(recipe_lines) + expect(IO).to receive(:readlines).at_least(1).times.with(/:\/opscode\/chef\/var\/cache\/cookbooks\/foo\/recipes\/default.rb/).and_return(recipe_lines) @trace = [ "C:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb:14 in `from_file'", "C:/opscode/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-10.14.0/lib/chef/run_context.rb:144:in `rescue in block in load_libraries'", @@ -131,7 +131,7 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do describe "and examining the stack trace for a recipe" do it "find the culprit recipe name when the drive letter is upper case" do - @inspector.culprit_file.should == "C:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb" + expect(@inspector.culprit_file).to eq("C:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb") end it "find the culprit recipe name when the drive letter is lower case" do @@ -139,12 +139,12 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do @exception.set_backtrace(@trace) @inspector = described_class.new(@path, @exception) @inspector.add_explanation(@description) - @inspector.culprit_file.should == "c:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb" + expect(@inspector.culprit_file).to eq("c:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb") end end it "finds the line number of the error from the stack trace" do - @inspector.culprit_line.should == 14 + expect(@inspector.culprit_line).to eq(14) end it "prints a pretty message" do @@ -154,9 +154,9 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do describe "when explaining an error on windows, and the backtrace lowercases the drive letter" do before do - Chef::Config.stub(:cookbook_path).and_return([ "C:/opscode/chef/var/cache/cookbooks" ]) + allow(Chef::Config).to receive(:cookbook_path).and_return([ "C:/opscode/chef/var/cache/cookbooks" ]) recipe_lines = BAD_RECIPE.split("\n").map {|l| l << "\n" } - IO.should_receive(:readlines).with("c:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb").and_return(recipe_lines) + expect(IO).to receive(:readlines).with("c:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb").and_return(recipe_lines) @trace = [ "c:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb:14 in `from_file'", "c:/opscode/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-10.14.0/lib/chef/run_context.rb:144:in `rescue in block in load_libraries'", @@ -187,11 +187,11 @@ describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do end it "finds the culprit recipe name from the stacktrace" do - @inspector.culprit_file.should == "c:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb" + expect(@inspector.culprit_file).to eq("c:/opscode/chef/var/cache/cookbooks/foo/recipes/default.rb") end it "finds the line number of the error from the stack trace" do - @inspector.culprit_line.should == 14 + expect(@inspector.culprit_line).to eq(14) end it "prints a pretty message" do diff --git a/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb index 06d45472e4..7e4d89f144 100644 --- a/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/cookbook_resolve_error_inspector_spec.rb @@ -34,7 +34,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do @response_body = %Q({"error": [{"message": "gtfo"}]) @response = Net::HTTPForbidden.new("1.1", "403", "(response) forbidden") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) forbidden", @response) @inspector = Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector.new(@expanded_run_list, @exception) @@ -42,7 +42,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do end it "prints a nice message" do - lambda { @description.display(@outputter) }.should_not raise_error + expect { @description.display(@outputter) }.not_to raise_error end end @@ -55,7 +55,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do @response_body = "{\"error\":[\"{\\\"non_existent_cookbooks\\\":[\\\"apache2\\\"],\\\"cookbooks_with_no_versions\\\":[\\\"users\\\"],\\\"message\\\":\\\"Run list contains invalid items: no such cookbook nope.\\\"}\"]}" @response = Net::HTTPPreconditionFailed.new("1.1", "412", "(response) unauthorized") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) precondition failed", @response) @inspector = Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector.new(@expanded_run_list, @exception) @@ -66,9 +66,9 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do @description.display(@outputter) @outputter_output.rewind observed_output = @outputter_output.read - observed_output.should include("apache2") - observed_output.should include("users") - observed_output.should_not include("Run list contains invalid items: no such cookbook nope.") + expect(observed_output).to include("apache2") + expect(observed_output).to include("users") + expect(observed_output).not_to include("Run list contains invalid items: no such cookbook nope.") end end @@ -83,7 +83,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do @response_body = "{\"error\":[{\"non_existent_cookbooks\":[],\"cookbooks_with_no_versions\":[],\"message\":\"unable to solve dependencies in alotted time.\"}]}" @response = Net::HTTPPreconditionFailed.new("1.1", "412", "(response) unauthorized") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) precondition failed", @response) @inspector = Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector.new(@expanded_run_list, @exception) @@ -93,7 +93,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do it "prints a pretty message" do @description.display(@outputter) @outputter_output.rewind - @outputter_output.read.should include("unable to solve dependencies in alotted time.") + expect(@outputter_output.read).to include("unable to solve dependencies in alotted time.") end end @@ -106,7 +106,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do @response_body = "{\"error\":[{\"non_existent_cookbooks\":[\"apache2\"],\"cookbooks_with_no_versions\":[\"users\"],\"message\":\"Run list contains invalid items: no such cookbook nope.\"}]}" @response = Net::HTTPPreconditionFailed.new("1.1", "412", "(response) unauthorized") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) precondition failed", @response) @inspector = Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector.new(@expanded_run_list, @exception) @@ -117,9 +117,9 @@ describe Chef::Formatters::ErrorInspectors::CookbookResolveErrorInspector do @description.display(@outputter) @outputter_output.rewind observed_output = @outputter_output.read - observed_output.should include("apache2") - observed_output.should include("users") - observed_output.should_not include("Run list contains invalid items: no such cookbook nope.") + expect(observed_output).to include("apache2") + expect(observed_output).to include("users") + expect(observed_output).not_to include("Run list contains invalid items: no such cookbook nope.") end end diff --git a/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb index 87c3708ef1..775a1838f3 100644 --- a/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb @@ -29,7 +29,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookSyncErrorInspector do before do @response_body = "sad trombone orchestra" @response = Net::HTTPBadGateway.new("1.1", "502", "(response) bad gateway") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPFatalError.new("(exception) bad gateway", @response) @inspector = described_class.new({}, @exception) @inspector.add_explanation(@description) diff --git a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb index 6691553ddd..ee957ed450 100644 --- a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb @@ -42,7 +42,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do @outputter = Chef::Formatters::IndentableOutputStream.new(@stdout, STDERR) #@outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR) - Chef::Config.stub(:cookbook_path).and_return([ "/var/chef/cache" ]) + allow(Chef::Config).to receive(:cookbook_path).and_return([ "/var/chef/cache" ]) end describe "when explaining an error converging a resource" do @@ -74,7 +74,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do "/var/chef/cache/cookbooks/syntax-err/recipes/default.rb:11:in `from_file'", ] - @inspector.filtered_bt.should == @expected_filtered_trace + expect(@inspector.filtered_bt).to eq(@expected_filtered_trace) end it "prints a pretty message" do @@ -105,7 +105,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do it "includes contextual info from the template error in the output" do @description.display(@outputter) - @stdout.string.should include(@error.source_listing) + expect(@stdout.string).to include(@error.source_listing) end @@ -115,40 +115,40 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do before do # fake code to run through #recipe_snippet source_file = [ "if true", "var = non_existant", "end" ] - IO.stub(:readlines).and_return(source_file) - File.stub(:exists?).and_return(true) + allow(IO).to receive(:readlines).and_return(source_file) + allow(File).to receive(:exists?).and_return(true) end it "parses a Windows path" do source_line = "C:/Users/btm/chef/chef/spec/unit/fake_file.rb:2: undefined local variable or method `non_existant' for main:Object (NameError)" @resource.source_line = source_line @inspector = Chef::Formatters::ErrorInspectors::ResourceFailureInspector.new(@resource, :create, @exception) - @inspector.recipe_snippet.should match(/^# In C:\/Users\/btm/) + expect(@inspector.recipe_snippet).to match(/^# In C:\/Users\/btm/) end it "parses a unix path" do source_line = "/home/btm/src/chef/chef/spec/unit/fake_file.rb:2: undefined local variable or method `non_existant' for main:Object (NameError)" @resource.source_line = source_line @inspector = Chef::Formatters::ErrorInspectors::ResourceFailureInspector.new(@resource, :create, @exception) - @inspector.recipe_snippet.should match(/^# In \/home\/btm/) + expect(@inspector.recipe_snippet).to match(/^# In \/home\/btm/) end context "when the recipe file does not exist" do before do - File.stub(:exists?).and_return(false) - IO.stub(:readlines).and_raise(Errno::ENOENT) + allow(File).to receive(:exists?).and_return(false) + allow(IO).to receive(:readlines).and_raise(Errno::ENOENT) end it "does not try to parse a recipe in chef-shell/irb (CHEF-3411)" do @resource.source_line = "(irb#1):1:in `irb_binding'" @inspector = Chef::Formatters::ErrorInspectors::ResourceFailureInspector.new(@resource, :create, @exception) - @inspector.recipe_snippet.should be_nil + expect(@inspector.recipe_snippet).to be_nil end it "does not raise an exception trying to load a non-existant file (CHEF-3411)" do @resource.source_line = "/somewhere/in/space" @inspector = Chef::Formatters::ErrorInspectors::ResourceFailureInspector.new(@resource, :create, @exception) - lambda { @inspector.recipe_snippet }.should_not raise_error + expect { @inspector.recipe_snippet }.not_to raise_error end end end @@ -175,7 +175,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do end it "does not generate an error" do - lambda { @inspector.add_explanation(@description) }.should_not raise_error + expect { @inspector.add_explanation(@description) }.not_to raise_error @description.display(@outputter) end end diff --git a/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb b/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb index 7f68c4fba4..1cd97596a7 100644 --- a/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb +++ b/spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb @@ -55,10 +55,10 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do @response_body = "forbidden" @response = Net::HTTPForbidden.new("1.1", "403", "(response) forbidden") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) forbidden", @response) @inspector = Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector.new(@node, @exception) - @inspector.stub(:config).and_return(:node_name => "unit-test.example.com") + allow(@inspector).to receive(:config).and_return(:node_name => "unit-test.example.com") @inspector.add_explanation(@description) end @@ -73,11 +73,11 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do before do @response_body = "check your key and node name" @response = Net::HTTPUnauthorized.new("1.1", "401", "(response) unauthorized") - @response.stub(:body).and_return(@response_body) + allow(@response).to receive(:body).and_return(@response_body) @exception = Net::HTTPServerException.new("(exception) unauthorized", @response) @inspector = Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector.new(@node, @exception) - @inspector.stub(:config).and_return(:node_name => "unit-test.example.com", + allow(@inspector).to receive(:config).and_return(:node_name => "unit-test.example.com", :client_key => "/etc/chef/client.pem", :chef_server_url => "http://chef.example.com") diff --git a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb index a122ac5515..9089177e18 100644 --- a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb +++ b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb @@ -31,8 +31,8 @@ describe Chef::GuardInterpreter::ResourceGuardInterpreter do let(:resource) do resource = Chef::Resource.new("powershell_unit_test", run_context) - resource.stub(:run_action) - resource.stub(:updated).and_return(true) + allow(resource).to receive(:run_action) + allow(resource).to receive(:updated).and_return(true) resource end diff --git a/spec/unit/handler/json_file_spec.rb b/spec/unit/handler/json_file_spec.rb index 05270e4731..f6c14a166e 100644 --- a/spec/unit/handler/json_file_spec.rb +++ b/spec/unit/handler/json_file_spec.rb @@ -24,12 +24,12 @@ describe Chef::Handler::JsonFile do end it "accepts arbitrary config options" do - @handler.config[:the_sun].should == "will rise" + expect(@handler.config[:the_sun]).to eq("will rise") end it "creates the directory where the reports will be saved" do - FileUtils.should_receive(:mkdir_p).with('/tmp/foobarbazqux') - File.should_receive(:chmod).with(00700, '/tmp/foobarbazqux') + expect(FileUtils).to receive(:mkdir_p).with('/tmp/foobarbazqux') + expect(File).to receive(:chmod).with(00700, '/tmp/foobarbazqux') @handler.build_report_dir end @@ -39,25 +39,25 @@ describe Chef::Handler::JsonFile do @events = Chef::EventDispatch::Dispatcher.new @run_status = Chef::RunStatus.new(@node, @events) @expected_time = Time.now - Time.stub(:now).and_return(@expected_time, @expected_time + 5) + allow(Time).to receive(:now).and_return(@expected_time, @expected_time + 5) @run_status.start_clock @run_status.stop_clock @run_context = Chef::RunContext.new(@node, {}, @events) @run_status.run_context = @run_context @run_status.exception = Exception.new("Boy howdy!") @file_mock = StringIO.new - File.stub(:open).and_yield(@file_mock) + allow(File).to receive(:open).and_yield(@file_mock) end it "saves run status data to a file as JSON" do - @handler.should_receive(:build_report_dir) + expect(@handler).to receive(:build_report_dir) @handler.run_report_unsafe(@run_status) reported_data = Chef::JSONCompat.from_json(@file_mock.string) - reported_data['exception'].should == "Exception: Boy howdy!" - reported_data['start_time'].should == @expected_time.to_s - reported_data['end_time'].should == (@expected_time + 5).to_s - reported_data['elapsed_time'].should == 5 + expect(reported_data['exception']).to eq("Exception: Boy howdy!") + expect(reported_data['start_time']).to eq(@expected_time.to_s) + expect(reported_data['end_time']).to eq((@expected_time + 5).to_s) + expect(reported_data['elapsed_time']).to eq(5) end end diff --git a/spec/unit/handler_spec.rb b/spec/unit/handler_spec.rb index 3a7e046dd5..a9aa0e0b50 100644 --- a/spec/unit/handler_spec.rb +++ b/spec/unit/handler_spec.rb @@ -42,54 +42,54 @@ describe Chef::Handler do @run_status.run_context = @run_context @start_time = Time.now @end_time = @start_time + 4.2 - Time.stub(:now).and_return(@start_time, @end_time) + allow(Time).to receive(:now).and_return(@start_time, @end_time) @run_status.start_clock @run_status.stop_clock end it "has a shortcut for the exception" do - @handler.exception.should == @exception + expect(@handler.exception).to eq(@exception) end it "has a shortcut for the backtrace" do - @handler.backtrace.should == @backtrace + expect(@handler.backtrace).to eq(@backtrace) end it "has a shortcut for all resources" do - @handler.all_resources.should == @all_resources + expect(@handler.all_resources).to eq(@all_resources) end it "has a shortcut for just the updated resources" do - @handler.updated_resources.should == [@all_resources.first] + expect(@handler.updated_resources).to eq([@all_resources.first]) end it "has a shortcut for the start time" do - @handler.start_time.should == @start_time + expect(@handler.start_time).to eq(@start_time) end it "has a shortcut for the end time" do - @handler.end_time.should == @end_time + expect(@handler.end_time).to eq(@end_time) end it "has a shortcut for the elapsed time" do - @handler.elapsed_time.should == 4.2 + expect(@handler.elapsed_time).to eq(4.2) end it "has a shortcut for the node" do - @handler.node.should == @node + expect(@handler.node).to eq(@node) end it "has a shortcut for the run context" do - @handler.run_context.should == @run_context + expect(@handler.run_context).to eq(@run_context) end it "has a shortcut for the success? and failed? predicates" do - @handler.success?.should be_false # becuase there's an exception - @handler.failed?.should be_true + expect(@handler.success?).to be_falsey # becuase there's an exception + expect(@handler.failed?).to be_truthy end it "has a shortcut to the hash representation of the run status" do - @handler.data.should == @run_status.to_hash + expect(@handler.data).to eq(@run_status.to_hash) end end @@ -100,16 +100,16 @@ describe Chef::Handler do $report_ran = true raise Exception, "I died the deth" end - lambda {@handler.run_report_safely(@run_status)}.should_not raise_error - $report_ran.should be_true + expect {@handler.run_report_safely(@run_status)}.not_to raise_error + expect($report_ran).to be_truthy end it "does not fail if the report handler does not raise an exception" do $report_ran = false def @handler.report $report_ran = true end - lambda {@handler.run_report_safely(@run_status)}.should_not raise_error - $report_ran.should be_true + expect {@handler.run_report_safely(@run_status)}.not_to raise_error + expect($report_ran).to be_truthy end end @@ -123,46 +123,46 @@ describe Chef::Handler do @run_status.run_context = @run_context @start_time = Time.now @end_time = @start_time + 4.2 - Time.stub(:now).and_return(@start_time, @end_time) + allow(Time).to receive(:now).and_return(@start_time, @end_time) @run_status.start_clock @run_status.stop_clock end it "has a shortcut for all resources" do - @handler.all_resources.should == @all_resources + expect(@handler.all_resources).to eq(@all_resources) end it "has a shortcut for just the updated resources" do - @handler.updated_resources.should == [@all_resources.first] + expect(@handler.updated_resources).to eq([@all_resources.first]) end it "has a shortcut for the start time" do - @handler.start_time.should == @start_time + expect(@handler.start_time).to eq(@start_time) end it "has a shortcut for the end time" do - @handler.end_time.should == @end_time + expect(@handler.end_time).to eq(@end_time) end it "has a shortcut for the elapsed time" do - @handler.elapsed_time.should == 4.2 + expect(@handler.elapsed_time).to eq(4.2) end it "has a shortcut for the node" do - @handler.node.should == @node + expect(@handler.node).to eq(@node) end it "has a shortcut for the run context" do - @handler.run_context.should == @run_context + expect(@handler.run_context).to eq(@run_context) end it "has a shortcut for the success? and failed? predicates" do - @handler.success?.should be_true - @handler.failed?.should be_false + expect(@handler.success?).to be_truthy + expect(@handler.failed?).to be_falsey end it "has a shortcut to the hash representation of the run status" do - @handler.data.should == @run_status.to_hash + expect(@handler.data).to eq(@run_status.to_hash) end end @@ -170,45 +170,45 @@ describe Chef::Handler do describe "when running a start handler" do before do @start_time = Time.now - Time.stub(:now).and_return(@start_time) + allow(Time).to receive(:now).and_return(@start_time) @run_status.start_clock end it "should not have all resources" do - @handler.all_resources.should be_false + expect(@handler.all_resources).to be_falsey end it "should not have updated resources" do - @handler.updated_resources.should be_false + expect(@handler.updated_resources).to be_falsey end it "has a shortcut for the start time" do - @handler.start_time.should == @start_time + expect(@handler.start_time).to eq(@start_time) end it "does not have a shortcut for the end time" do - @handler.end_time.should be_false + expect(@handler.end_time).to be_falsey end it "does not have a shortcut for the elapsed time" do - @handler.elapsed_time.should be_false + expect(@handler.elapsed_time).to be_falsey end it "has a shortcut for the node" do - @handler.node.should == @node + expect(@handler.node).to eq(@node) end it "does not have a shortcut for the run context" do - @handler.run_context.should be_false + expect(@handler.run_context).to be_falsey end it "has a shortcut for the success? and failed? predicates" do - @handler.success?.should be_true # for some reason this is true - @handler.failed?.should be_false + expect(@handler.success?).to be_truthy # for some reason this is true + expect(@handler.failed?).to be_falsey end it "has a shortcut to the hash representation of the run status" do - @handler.data.should == @run_status.to_hash + expect(@handler.data).to eq(@run_status.to_hash) end end diff --git a/spec/unit/http/basic_client_spec.rb b/spec/unit/http/basic_client_spec.rb index cb1f2fd979..eb133f943e 100644 --- a/spec/unit/http/basic_client_spec.rb +++ b/spec/unit/http/basic_client_spec.rb @@ -35,7 +35,7 @@ describe "HTTP Connection" do end it "should set an open timeout" do - subject.build_http_client.open_timeout.should_not be_nil + expect(subject.build_http_client.open_timeout).not_to be_nil end end @@ -52,12 +52,12 @@ describe "HTTP Connection" do it "should contain the host" do proxy_uri = subject.proxy_uri - proxy_uri.host.should == proxy_host + expect(proxy_uri.host).to eq(proxy_host) end it "should contain the port" do proxy_uri = subject.proxy_uri - proxy_uri.port.should == proxy_port + expect(proxy_uri.port).to eq(proxy_port) end end diff --git a/spec/unit/http/http_request_spec.rb b/spec/unit/http/http_request_spec.rb index d573d4c5dc..3bba201963 100644 --- a/spec/unit/http/http_request_spec.rb +++ b/spec/unit/http/http_request_spec.rb @@ -25,31 +25,31 @@ describe Chef::HTTP::HTTPRequest do it "should not include port 80 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('http://dummy.com'), '') - request.headers['Host'].should eql('dummy.com') + expect(request.headers['Host']).to eql('dummy.com') end it "should not include explicit port 80 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('http://dummy.com:80'), '') - request.headers['Host'].should eql('dummy.com') + expect(request.headers['Host']).to eql('dummy.com') end it "should include explicit port 8000 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('http://dummy.com:8000'), '') - request.headers['Host'].should eql('dummy.com:8000') + expect(request.headers['Host']).to eql('dummy.com:8000') end it "should include explicit 443 port in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('http://dummy.com:443'), '') - request.headers['Host'].should eql('dummy.com:443') + expect(request.headers['Host']).to eql('dummy.com:443') end it "should pass on explicit Host header unchanged" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('http://dummy.com:8000'), '', { 'Host' => 'yourhost.com:8888' }) - request.headers['Host'].should eql('yourhost.com:8888') + expect(request.headers['Host']).to eql('yourhost.com:8888') end end @@ -59,25 +59,25 @@ describe Chef::HTTP::HTTPRequest do it "should not include port 443 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('https://dummy.com'), '') - request.headers['Host'].should eql('dummy.com') + expect(request.headers['Host']).to eql('dummy.com') end it "should include explicit port 80 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('https://dummy.com:80'), '') - request.headers['Host'].should eql('dummy.com:80') + expect(request.headers['Host']).to eql('dummy.com:80') end it "should include explicit port 8000 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('https://dummy.com:8000'), '') - request.headers['Host'].should eql('dummy.com:8000') + expect(request.headers['Host']).to eql('dummy.com:8000') end it "should not include explicit port 443 in Host header" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('https://dummy.com:443'), '') - request.headers['Host'].should eql('dummy.com') + expect(request.headers['Host']).to eql('dummy.com') end end @@ -85,7 +85,7 @@ describe Chef::HTTP::HTTPRequest do it "should pass on explicit Host header unchanged" do request = Chef::HTTP::HTTPRequest.new(:GET, URI('http://dummy.com:8000'), '', { 'Host' => 'myhost.com:80' }) - request.headers['Host'].should eql('myhost.com:80') + expect(request.headers['Host']).to eql('myhost.com:80') end end diff --git a/spec/unit/http/simple_spec.rb b/spec/unit/http/simple_spec.rb index b33ef1d553..c8fb52e8b2 100644 --- a/spec/unit/http/simple_spec.rb +++ b/spec/unit/http/simple_spec.rb @@ -25,8 +25,8 @@ describe Chef::HTTP::Simple do content_length = middlewares.find_index { |e| e.is_a? Chef::HTTP::ValidateContentLength } decompressor = middlewares.find_index { |e| e.is_a? Chef::HTTP::Decompressor } - content_length.should_not be_nil - decompressor.should_not be_nil - (decompressor < content_length).should be_true + expect(content_length).not_to be_nil + expect(decompressor).not_to be_nil + expect(decompressor < content_length).to be_truthy end end diff --git a/spec/unit/http/ssl_policies_spec.rb b/spec/unit/http/ssl_policies_spec.rb index b95e13a370..5ebebf39b1 100644 --- a/spec/unit/http/ssl_policies_spec.rb +++ b/spec/unit/http/ssl_policies_spec.rb @@ -45,31 +45,31 @@ describe "HTTP SSL Policy" do end it "configures the HTTP client to use SSL when given a URL with the https protocol" do - http_client.use_ssl?.should be_true + expect(http_client.use_ssl?).to be_truthy end it "sets the OpenSSL verify mode to verify_peer" do - http_client.verify_mode.should == OpenSSL::SSL::VERIFY_PEER + expect(http_client.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) end it "raises a ConfigurationError if :ssl_ca_path is set to a path that doesn't exist" do Chef::Config[:ssl_ca_path] = "/dev/null/nothing_here" - lambda {http_client}.should raise_error(Chef::Exceptions::ConfigurationError) + expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) end it "should set the CA path if that is set in the configuration" do Chef::Config[:ssl_ca_path] = File.join(CHEF_SPEC_DATA, "ssl") - http_client.ca_path.should == File.join(CHEF_SPEC_DATA, "ssl") + expect(http_client.ca_path).to eq(File.join(CHEF_SPEC_DATA, "ssl")) end it "raises a ConfigurationError if :ssl_ca_file is set to a file that does not exist" do Chef::Config[:ssl_ca_file] = "/dev/null/nothing_here" - lambda {http_client}.should raise_error(Chef::Exceptions::ConfigurationError) + expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) end it "should set the CA file if that is set in the configuration" do Chef::Config[:ssl_ca_file] = CHEF_SPEC_DATA + '/ssl/5e707473.0' - http_client.ca_file.should == CHEF_SPEC_DATA + '/ssl/5e707473.0' + expect(http_client.ca_file).to eq(CHEF_SPEC_DATA + '/ssl/5e707473.0') end end @@ -80,7 +80,7 @@ describe "HTTP SSL Policy" do end it "sets the OpenSSL verify mode to :verify_none" do - http_client.verify_mode.should == OpenSSL::SSL::VERIFY_NONE + expect(http_client.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) end end @@ -90,26 +90,26 @@ describe "HTTP SSL Policy" do it "raises ConfigurationError if the certificate file doesn't exist" do Chef::Config[:ssl_client_cert] = "/dev/null/nothing_here" Chef::Config[:ssl_client_key] = CHEF_SPEC_DATA + '/ssl/chef-rspec.key' - lambda {http_client}.should raise_error(Chef::Exceptions::ConfigurationError) + expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) end it "raises ConfigurationError if the certificate file doesn't exist" do Chef::Config[:ssl_client_cert] = CHEF_SPEC_DATA + '/ssl/chef-rspec.cert' Chef::Config[:ssl_client_key] = "/dev/null/nothing_here" - lambda {http_client}.should raise_error(Chef::Exceptions::ConfigurationError) + expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) end it "raises a ConfigurationError if one of :ssl_client_cert and :ssl_client_key is set but not both" do Chef::Config[:ssl_client_cert] = "/dev/null/nothing_here" Chef::Config[:ssl_client_key] = nil - lambda {http_client}.should raise_error(Chef::Exceptions::ConfigurationError) + expect {http_client}.to raise_error(Chef::Exceptions::ConfigurationError) end it "configures the HTTP client's cert and private key" do Chef::Config[:ssl_client_cert] = CHEF_SPEC_DATA + '/ssl/chef-rspec.cert' Chef::Config[:ssl_client_key] = CHEF_SPEC_DATA + '/ssl/chef-rspec.key' - http_client.cert.to_s.should == OpenSSL::X509::Certificate.new(IO.read(CHEF_SPEC_DATA + '/ssl/chef-rspec.cert')).to_s - http_client.key.to_s.should == IO.read(CHEF_SPEC_DATA + '/ssl/chef-rspec.key') + expect(http_client.cert.to_s).to eq(OpenSSL::X509::Certificate.new(IO.read(CHEF_SPEC_DATA + '/ssl/chef-rspec.cert')).to_s) + expect(http_client.key.to_s).to eq(IO.read(CHEF_SPEC_DATA + '/ssl/chef-rspec.key')) end end @@ -125,7 +125,7 @@ describe "HTTP SSL Policy" do end it "enables verification of self-signed certificates" do - http_client.cert_store.verify(self_signed_crt).should be_true + expect(http_client.cert_store.verify(self_signed_crt)).to be_truthy end it "enables verification of cert chains" do @@ -137,7 +137,7 @@ describe "HTTP SSL Policy" do # If the machine running the test doesn't have ruby SSL configured correctly, # then the root cert also has to be loaded for the test to succeed. # The system under test **SHOULD** do both of these things. - http_client.cert_store.verify(additional_pem).should be_true + expect(http_client.cert_store.verify(additional_pem)).to be_truthy end context "and some certs are duplicates" do @@ -161,7 +161,7 @@ describe "HTTP SSL Policy" do end it "sets the OpenSSL verify mode to verify_peer" do - http_client.verify_mode.should == OpenSSL::SSL::VERIFY_PEER + expect(http_client.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) end end diff --git a/spec/unit/http/validate_content_length_spec.rb b/spec/unit/http/validate_content_length_spec.rb index 091f2b0757..34b6a61a3a 100644 --- a/spec/unit/http/validate_content_length_spec.rb +++ b/spec/unit/http/validate_content_length_spec.rb @@ -45,7 +45,7 @@ describe Chef::HTTP::ValidateContentLength do let(:response) { m = double('HttpResponse', :body => response_body) - m.stub(:[]) do |key| + allow(m).to receive(:[]) do |key| response_headers[key] end @@ -85,7 +85,7 @@ describe Chef::HTTP::ValidateContentLength do before(:each) { Chef::Log.level = :debug - Chef::Log.stub(:debug) do |message| + allow(Chef::Log).to receive(:debug) do |message| debug_stream.puts message end } @@ -95,7 +95,7 @@ describe Chef::HTTP::ValidateContentLength do let(:response_body) { "Thanks for checking in." } it "shouldn't raise error" do - lambda { run_content_length_validation }.should_not raise_error + expect { run_content_length_validation }.not_to raise_error end end @@ -108,7 +108,7 @@ describe Chef::HTTP::ValidateContentLength do it "should skip validation and log for debug" do run_content_length_validation - debug_output.should include("HTTP server did not include a Content-Length header in response") + expect(debug_output).to include("HTTP server did not include a Content-Length header in response") end end end @@ -121,7 +121,7 @@ describe Chef::HTTP::ValidateContentLength do it "should validate correctly" do run_content_length_validation - debug_output.should include("Content-Length validated correctly.") + expect(debug_output).to include("Content-Length validated correctly.") end end end @@ -134,7 +134,7 @@ describe Chef::HTTP::ValidateContentLength do let(:request_type) { req_type.to_sym } it "should raise ContentLengthMismatch error" do - lambda { run_content_length_validation }.should raise_error(Chef::Exceptions::ContentLengthMismatch) + expect { run_content_length_validation }.to raise_error(Chef::Exceptions::ContentLengthMismatch) end end end @@ -144,7 +144,7 @@ describe Chef::HTTP::ValidateContentLength do let(:streaming_length) { 12 } it "should raise ContentLengthMismatch error" do - lambda { run_content_length_validation }.should raise_error(Chef::Exceptions::ContentLengthMismatch) + expect { run_content_length_validation }.to raise_error(Chef::Exceptions::ContentLengthMismatch) end end @@ -162,7 +162,7 @@ describe Chef::HTTP::ValidateContentLength do it "should skip validation and log for debug" do run_content_length_validation - debug_output.should include("Transfer-Encoding header is set, skipping Content-Length check.") + expect(debug_output).to include("Transfer-Encoding header is set, skipping Content-Length check.") end end end @@ -171,16 +171,16 @@ describe Chef::HTTP::ValidateContentLength do describe "when client is being reused" do before do run_content_length_validation - debug_output.should include("Content-Length validated correctly.") + expect(debug_output).to include("Content-Length validated correctly.") end it "should reset internal counter" do - middleware.instance_variable_get(:@content_length_counter).should be_nil + expect(middleware.instance_variable_get(:@content_length_counter)).to be_nil end it "should validate correctly second time" do run_content_length_validation - debug_output.should include("Content-Length validated correctly.") + expect(debug_output).to include("Content-Length validated correctly.") end end diff --git a/spec/unit/http_spec.rb b/spec/unit/http_spec.rb index 1cd226b4ee..60d36eb4a0 100644 --- a/spec/unit/http_spec.rb +++ b/spec/unit/http_spec.rb @@ -31,17 +31,17 @@ describe Chef::HTTP do it 'should return a correctly formatted url 1/3 CHEF-5261' do http = Chef::HTTP.new('http://www.getchef.com') - http.create_url('api/endpoint').should eql(URI.parse('http://www.getchef.com/api/endpoint')) + expect(http.create_url('api/endpoint')).to eql(URI.parse('http://www.getchef.com/api/endpoint')) end it 'should return a correctly formatted url 2/3 CHEF-5261' do http = Chef::HTTP.new('http://www.getchef.com/') - http.create_url('/organization/org/api/endpoint/').should eql(URI.parse('http://www.getchef.com/organization/org/api/endpoint/')) + expect(http.create_url('/organization/org/api/endpoint/')).to eql(URI.parse('http://www.getchef.com/organization/org/api/endpoint/')) end it 'should return a correctly formatted url 3/3 CHEF-5261' do http = Chef::HTTP.new('http://www.getchef.com/organization/org///') - http.create_url('///api/endpoint?url=http://foo.bar').should eql(URI.parse('http://www.getchef.com/organization/org/api/endpoint?url=http://foo.bar')) + expect(http.create_url('///api/endpoint?url=http://foo.bar')).to eql(URI.parse('http://www.getchef.com/organization/org/api/endpoint?url=http://foo.bar')) end end # create_url @@ -50,20 +50,20 @@ describe Chef::HTTP do it 'should return nil for a "200 Success" response (CHEF-4762)' do resp = Net::HTTPOK.new("1.1", 200, "OK") - resp.should_receive(:read_body).and_return(nil) + expect(resp).to receive(:read_body).and_return(nil) http = Chef::HTTP.new("") - Chef::HTTP::BasicClient.any_instance.should_receive(:request).and_return(["request", resp]) + expect_any_instance_of(Chef::HTTP::BasicClient).to receive(:request).and_return(["request", resp]) - http.head("http://www.getchef.com/").should eql(nil) + expect(http.head("http://www.getchef.com/")).to eql(nil) end it 'should return false for a "304 Not Modified" response (CHEF-4762)' do resp = Net::HTTPNotModified.new("1.1", 304, "Not Modified") - resp.should_receive(:read_body).and_return(nil) + expect(resp).to receive(:read_body).and_return(nil) http = Chef::HTTP.new("") - Chef::HTTP::BasicClient.any_instance.should_receive(:request).and_return(["request", resp]) + expect_any_instance_of(Chef::HTTP::BasicClient).to receive(:request).and_return(["request", resp]) - http.head("http://www.getchef.com/").should eql(false) + expect(http.head("http://www.getchef.com/")).to eql(false) end end # head diff --git a/spec/unit/knife/bootstrap_spec.rb b/spec/unit/knife/bootstrap_spec.rb index 2599e44a56..4de2b4531d 100644 --- a/spec/unit/knife/bootstrap_spec.rb +++ b/spec/unit/knife/bootstrap_spec.rb @@ -23,7 +23,7 @@ require 'net/ssh' describe Chef::Knife::Bootstrap do before do - Chef::Platform.stub(:windows?) { false } + allow(Chef::Platform).to receive(:windows?) { false } end let(:knife) do Chef::Log.logger = Logger.new(StringIO.new) @@ -32,7 +32,7 @@ describe Chef::Knife::Bootstrap do k = Chef::Knife::Bootstrap.new k.merge_configs - k.ui.stub(:stderr).and_return(stderr) + allow(k.ui).to receive(:stderr).and_return(stderr) allow(k).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(false) k end @@ -42,8 +42,8 @@ describe Chef::Knife::Bootstrap do let(:bootstrap_template) { nil } it "should use chef-full as default template" do - knife.bootstrap_template.should be_a_kind_of(String) - File.basename(knife.bootstrap_template).should eq("chef-full") + expect(knife.bootstrap_template).to be_a_kind_of(String) + expect(File.basename(knife.bootstrap_template)).to eq("chef-full") end context "when finding templates" do @@ -52,7 +52,7 @@ describe Chef::Knife::Bootstrap do let(:bootstrap_template) { "/opt/blah/not/exists/template.erb" } it "raises an error" do - lambda { knife.find_template }.should raise_error + expect { knife.find_template }.to raise_error end end @@ -60,8 +60,8 @@ describe Chef::Knife::Bootstrap do let(:bootstrap_template) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb")) } it "loads the given file as the template" do - Chef::Log.should_receive(:debug) - knife.find_template.should eq(File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb"))) + expect(Chef::Log).to receive(:debug) + expect(knife.find_template).to eq(File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb"))) end end end @@ -78,7 +78,7 @@ describe Chef::Knife::Bootstrap do let(:gem_files_template_path) { "/Users/schisamo/.rvm/gems/ruby-1.9.2-p180@chef-0.10/gems/knife-windows-0.5.4/lib/chef/knife/bootstrap/fake-bootstrap-template.erb" } def configure_chef_config_dir - Chef::Knife.stub(:chef_config_dir).and_return("/knife/chef/config") + allow(Chef::Knife).to receive(:chef_config_dir).and_return("/knife/chef/config") end def configure_env_home @@ -86,13 +86,13 @@ describe Chef::Knife::Bootstrap do end def configure_gem_files - Gem.stub(:find_files).and_return([ gem_files_template_path ]) + allow(Gem).to receive(:find_files).and_return([ gem_files_template_path ]) end before(:each) do @original_home = ENV['HOME'] ENV['HOME'] = nil - File.should_receive(:exists?).with(bootstrap_template).and_return(false) + expect(File).to receive(:exists?).with(bootstrap_template).and_return(false) end after(:each) do @@ -105,11 +105,11 @@ describe Chef::Knife::Bootstrap do configure_env_home configure_gem_files - File.should_receive(:exists?).with(builtin_template_path).and_return(true) + expect(File).to receive(:exists?).with(builtin_template_path).and_return(true) end it "should load the template from built-in templates" do - knife.find_template.should eq(builtin_template_path) + expect(knife.find_template).to eq(builtin_template_path) end end @@ -119,8 +119,8 @@ describe Chef::Knife::Bootstrap do configure_env_home configure_gem_files - File.should_receive(:exists?).with(builtin_template_path).and_return(false) - File.should_receive(:exists?).with(chef_config_dir_template_path).and_return(true) + expect(File).to receive(:exists?).with(builtin_template_path).and_return(false) + expect(File).to receive(:exists?).with(chef_config_dir_template_path).and_return(true) it "should load the template from chef_config_dir" do knife.find_template.should eq(chef_config_dir_template_path) @@ -134,13 +134,13 @@ describe Chef::Knife::Bootstrap do configure_env_home configure_gem_files - File.should_receive(:exists?).with(builtin_template_path).and_return(false) - File.should_receive(:exists?).with(chef_config_dir_template_path).and_return(false) - File.should_receive(:exists?).with(env_home_template_path).and_return(true) + expect(File).to receive(:exists?).with(builtin_template_path).and_return(false) + expect(File).to receive(:exists?).with(chef_config_dir_template_path).and_return(false) + expect(File).to receive(:exists?).with(env_home_template_path).and_return(true) end it "should load the template from chef_config_dir" do - knife.find_template.should eq(env_home_template_path) + expect(knife.find_template).to eq(env_home_template_path) end end @@ -149,13 +149,13 @@ describe Chef::Knife::Bootstrap do configure_chef_config_dir configure_gem_files - File.should_receive(:exists?).with(builtin_template_path).and_return(false) - File.should_receive(:exists?).with(chef_config_dir_template_path).and_return(false) - File.should_receive(:exists?).with(gem_files_template_path).and_return(true) + expect(File).to receive(:exists?).with(builtin_template_path).and_return(false) + expect(File).to receive(:exists?).with(chef_config_dir_template_path).and_return(false) + expect(File).to receive(:exists?).with(gem_files_template_path).and_return(true) end it "should load the template from Gem files" do - knife.find_template.should eq(gem_files_template_path) + expect(knife.find_template).to eq(gem_files_template_path) end end end @@ -166,7 +166,7 @@ describe Chef::Knife::Bootstrap do it "sets the knife :bootstrap_template config" do knife.parse_options([t,"blahblah"]) knife.merge_configs - knife.bootstrap_template.should eq("blahblah") + expect(knife.bootstrap_template).to eq("blahblah") end end end @@ -175,19 +175,19 @@ describe Chef::Knife::Bootstrap do let(:bootstrap_template) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb")) } it "should return an empty run_list" do - knife.render_template.should == '{"run_list":[]}' + expect(knife.render_template).to eq('{"run_list":[]}') end it "should have role[base] in the run_list" do knife.parse_options(["-r","role[base]"]) knife.merge_configs - knife.render_template.should == '{"run_list":["role[base]"]}' + expect(knife.render_template).to eq('{"run_list":["role[base]"]}') end it "should have role[base] and recipe[cupcakes] in the run_list" do knife.parse_options(["-r", "role[base],recipe[cupcakes]"]) knife.merge_configs - knife.render_template.should == '{"run_list":["role[base]","recipe[cupcakes]"]}' + expect(knife.render_template).to eq('{"run_list":["role[base]","recipe[cupcakes]"]}') end it "should have foo => {bar => baz} in the first_boot" do @@ -195,7 +195,7 @@ describe Chef::Knife::Bootstrap do knife.merge_configs expected_hash = FFI_Yajl::Parser.new.parse('{"foo":{"bar":"baz"},"run_list":[]}') actual_hash = FFI_Yajl::Parser.new.parse(knife.render_template) - actual_hash.should == expected_hash + expect(actual_hash).to eq(expected_hash) end end @@ -205,14 +205,14 @@ describe Chef::Knife::Bootstrap do it "should create a hint file when told to" do knife.parse_options(["--hint", "openstack"]) knife.merge_configs - knife.render_template.should match /\/etc\/chef\/ohai\/hints\/openstack.json/ + expect(knife.render_template).to match /\/etc\/chef\/ohai\/hints\/openstack.json/ end it "should populate a hint file with JSON when given a file to read" do - ::File.stub(:read).and_return('{ "foo" : "bar" }') + allow(::File).to receive(:read).and_return('{ "foo" : "bar" }') knife.parse_options(["--hint", "openstack=hints/openstack.json"]) knife.merge_configs - knife.render_template.should match /\{\"foo\":\"bar\"\}/ + expect(knife.render_template).to match /\{\"foo\":\"bar\"\}/ end end @@ -235,7 +235,7 @@ describe Chef::Knife::Bootstrap do let(:setting) { "api.opscode.com" } it "renders the client.rb with a single FQDN no_proxy entry" do - rendered_template.should match(%r{.*no_proxy\s*"api.opscode.com".*}) + expect(rendered_template).to match(%r{.*no_proxy\s*"api.opscode.com".*}) end end @@ -243,7 +243,7 @@ describe Chef::Knife::Bootstrap do let(:setting) { "api.opscode.com,172.16.10.*" } it "renders the client.rb with comma-separated FQDN and wildcard IP address no_proxy entries" do - rendered_template.should match(%r{.*no_proxy\s*"api.opscode.com,172.16.10.\*".*}) + expect(rendered_template).to match(%r{.*no_proxy\s*"api.opscode.com,172.16.10.\*".*}) end end @@ -251,7 +251,7 @@ describe Chef::Knife::Bootstrap do let(:options) { ["--node-ssl-verify-mode", "none"] } it "renders the client.rb with ssl_verify_mode set to :verify_none" do - rendered_template.should match(/ssl_verify_mode :verify_none/) + expect(rendered_template).to match(/ssl_verify_mode :verify_none/) end end @@ -259,7 +259,7 @@ describe Chef::Knife::Bootstrap do let(:options) { ["--node-ssl-verify-mode", "peer"] } it "renders the client.rb with ssl_verify_mode set to :verify_peer" do - rendered_template.should match(/ssl_verify_mode :verify_peer/) + expect(rendered_template).to match(/ssl_verify_mode :verify_peer/) end end @@ -267,7 +267,7 @@ describe Chef::Knife::Bootstrap do let(:options) { ["--node-ssl-verify-mode", "all"] } it "raises error" do - lambda{ rendered_template }.should raise_error + expect{ rendered_template }.to raise_error end end @@ -275,7 +275,7 @@ describe Chef::Knife::Bootstrap do let(:options) { ["--node-verify-api-cert"] } it "renders the client.rb with verify_api_cert set to true" do - rendered_template.should match(/verify_api_cert true/) + expect(rendered_template).to match(/verify_api_cert true/) end end @@ -283,7 +283,7 @@ describe Chef::Knife::Bootstrap do let(:options) { ["--no-node-verify-api-cert"] } it "renders the client.rb with verify_api_cert set to false" do - rendered_template.should match(/verify_api_cert false/) + expect(rendered_template).to match(/verify_api_cert false/) end end end @@ -301,13 +301,13 @@ describe Chef::Knife::Bootstrap do it "creates a secret file" do expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(true) expect(knife).to receive(:read_secret).and_return(secret) - rendered_template.should match(%r{#{secret}}) + expect(rendered_template).to match(%r{#{secret}}) end it "renders the client.rb with an encrypted_data_bag_secret entry" do expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(true) expect(knife).to receive(:read_secret).and_return(secret) - rendered_template.should match(%r{encrypted_data_bag_secret\s*"/etc/chef/encrypted_data_bag_secret"}) + expect(rendered_template).to match(%r{encrypted_data_bag_secret\s*"/etc/chef/encrypted_data_bag_secret"}) end end @@ -322,8 +322,8 @@ describe Chef::Knife::Bootstrap do before do Chef::Config[:trusted_certs_dir] = trusted_certs_dir - IO.stub(:read).and_call_original - IO.stub(:read).with(File.expand_path(Chef::Config[:validation_key])).and_return("") + allow(IO).to receive(:read).and_call_original + allow(IO).to receive(:read).with(File.expand_path(Chef::Config[:validation_key])).and_return("") end def certificates @@ -331,22 +331,22 @@ describe Chef::Knife::Bootstrap do end it "creates /etc/chef/trusted_certs" do - rendered_template.should match(%r{mkdir -p /etc/chef/trusted_certs}) + expect(rendered_template).to match(%r{mkdir -p /etc/chef/trusted_certs}) end it "copies the certificates in the directory" do certificates.each do |cert| - IO.should_receive(:read).with(File.expand_path(cert)) + expect(IO).to receive(:read).with(File.expand_path(cert)) end certificates.each do |cert| - rendered_template.should match(%r{cat > /etc/chef/trusted_certs/#{File.basename(cert)} <<'EOP'}) + expect(rendered_template).to match(%r{cat > /etc/chef/trusted_certs/#{File.basename(cert)} <<'EOP'}) end end it "doesn't create /etc/chef/trusted_certs if :trusted_certs_dir is empty" do - Dir.should_receive(:glob).with(File.join(trusted_certs_dir, "*.{crt,pem}")).and_return([]) - rendered_template.should_not match(%r{mkdir -p /etc/chef/trusted_certs}) + expect(Dir).to receive(:glob).with(File.join(trusted_certs_dir, "*.{crt,pem}")).and_return([]) + expect(rendered_template).not_to match(%r{mkdir -p /etc/chef/trusted_certs}) end end @@ -361,57 +361,57 @@ describe Chef::Knife::Bootstrap do Chef::Config[:knife][:ssh_port] = nil knife.config[:forward_agent] = true knife.config[:identity_file] = "~/.ssh/me.rsa" - knife.stub(:render_template).and_return("") + allow(knife).to receive(:render_template).and_return("") knife.knife_ssh end it "configures the hostname" do - knife_ssh.name_args.first.should == "foo.example.com" + expect(knife_ssh.name_args.first).to eq("foo.example.com") end it "configures the ssh user" do - knife_ssh.config[:ssh_user].should == 'rooty' + expect(knife_ssh.config[:ssh_user]).to eq('rooty') end it "configures the ssh password" do - knife_ssh.config[:ssh_password].should == 'open_sesame' + expect(knife_ssh.config[:ssh_password]).to eq('open_sesame') end it "configures the ssh port" do - knife_ssh.config[:ssh_port].should == '4001' + expect(knife_ssh.config[:ssh_port]).to eq('4001') end it "configures the ssh agent forwarding" do - knife_ssh.config[:forward_agent].should == true + expect(knife_ssh.config[:forward_agent]).to eq(true) end it "configures the ssh identity file" do - knife_ssh.config[:identity_file].should == '~/.ssh/me.rsa' + expect(knife_ssh.config[:identity_file]).to eq('~/.ssh/me.rsa') end end context "validating use_sudo_password" do before do knife.config[:ssh_password] = "password" - knife.stub(:render_template).and_return("") + allow(knife).to receive(:render_template).and_return("") end it "use_sudo_password contains description and long params for help" do - knife.options.should have_key(:use_sudo_password) \ - and knife.options[:use_sudo_password][:description].to_s.should_not == ''\ - and knife.options[:use_sudo_password][:long].to_s.should_not == '' + expect(knife.options).to have_key(:use_sudo_password) \ + and expect(knife.options[:use_sudo_password][:description].to_s).not_to eq('')\ + and expect(knife.options[:use_sudo_password][:long].to_s).not_to eq('') end it "uses the password from --ssh-password for sudo when --use-sudo-password is set" do knife.config[:use_sudo] = true knife.config[:use_sudo_password] = true - knife.ssh_command.should include("echo \'#{knife.config[:ssh_password]}\' | sudo -S") + expect(knife.ssh_command).to include("echo \'#{knife.config[:ssh_password]}\' | sudo -S") end it "should not honor --use-sudo-password when --use-sudo is not set" do knife.config[:use_sudo] = false knife.config[:use_sudo_password] = true - knife.ssh_command.should_not include("echo #{knife.config[:ssh_password]} | sudo -S") + expect(knife.ssh_command).not_to include("echo #{knife.config[:ssh_password]} | sudo -S") end end @@ -424,34 +424,34 @@ describe Chef::Knife::Bootstrap do Chef::Config[:knife][:identity_file] = "~/.ssh/you.rsa" Chef::Config[:knife][:ssh_gateway] = "towel.blinkenlights.nl" Chef::Config[:knife][:host_key_verify] = true - knife.stub(:render_template).and_return("") + allow(knife).to receive(:render_template).and_return("") knife.config = {} knife.merge_configs knife.knife_ssh end it "configures the ssh user" do - knife_ssh.config[:ssh_user].should == 'curiosity' + expect(knife_ssh.config[:ssh_user]).to eq('curiosity') end it "configures the ssh port" do - knife_ssh.config[:ssh_port].should == '2430' + expect(knife_ssh.config[:ssh_port]).to eq('2430') end it "configures the ssh agent forwarding" do - knife_ssh.config[:forward_agent].should == true + expect(knife_ssh.config[:forward_agent]).to eq(true) end it "configures the ssh identity file" do - knife_ssh.config[:identity_file].should == '~/.ssh/you.rsa' + expect(knife_ssh.config[:identity_file]).to eq('~/.ssh/you.rsa') end it "configures the ssh gateway" do - knife_ssh.config[:ssh_gateway].should == 'towel.blinkenlights.nl' + expect(knife_ssh.config[:ssh_gateway]).to eq('towel.blinkenlights.nl') end it "configures the host key verify mode" do - knife_ssh.config[:host_key_verify].should == true + expect(knife_ssh.config[:host_key_verify]).to eq(true) end end @@ -460,27 +460,27 @@ describe Chef::Knife::Bootstrap do knife.name_args = ["foo.example.com"] knife.config[:ssh_user] = "rooty" knife.config[:identity_file] = "~/.ssh/me.rsa" - knife.stub(:render_template).and_return("") + allow(knife).to receive(:render_template).and_return("") k = knife.knife_ssh - k.stub(:get_password).and_return('typed_in_password') - knife.stub(:knife_ssh).and_return(k) + allow(k).to receive(:get_password).and_return('typed_in_password') + allow(knife).to receive(:knife_ssh).and_return(k) knife.knife_ssh_with_password_auth end it "prompts the user for a password " do - knife_ssh_with_password_auth.config[:ssh_password].should == 'typed_in_password' + expect(knife_ssh_with_password_auth.config[:ssh_password]).to eq('typed_in_password') end it "configures knife not to use the identity file that didn't work previously" do - knife_ssh_with_password_auth.config[:identity_file].should be_nil + expect(knife_ssh_with_password_auth.config[:identity_file]).to be_nil end end end it "verifies that a server to bootstrap was given as a command line arg" do knife.name_args = nil - lambda { knife.run }.should raise_error(SystemExit) - stderr.string.should match /ERROR:.+FQDN or ip/ + expect { knife.run }.to raise_error(SystemExit) + expect(stderr.string).to match /ERROR:.+FQDN or ip/ end describe "when running the bootstrap" do @@ -488,31 +488,31 @@ describe Chef::Knife::Bootstrap do knife.name_args = ["foo.example.com"] knife.config[:ssh_user] = "rooty" knife.config[:identity_file] = "~/.ssh/me.rsa" - knife.stub(:render_template).and_return("") + allow(knife).to receive(:render_template).and_return("") knife_ssh = knife.knife_ssh - knife.stub(:knife_ssh).and_return(knife_ssh) + allow(knife).to receive(:knife_ssh).and_return(knife_ssh) knife_ssh end it "configures the underlying ssh command and then runs it" do - knife_ssh.should_receive(:run) + expect(knife_ssh).to receive(:run) knife.run end it "falls back to password based auth when auth fails the first time" do - knife.stub(:puts) + allow(knife).to receive(:puts) fallback_knife_ssh = knife_ssh.dup - knife_ssh.should_receive(:run).and_raise(Net::SSH::AuthenticationFailed.new("no ssh for you")) - knife.stub(:knife_ssh_with_password_auth).and_return(fallback_knife_ssh) - fallback_knife_ssh.should_receive(:run) + expect(knife_ssh).to receive(:run).and_raise(Net::SSH::AuthenticationFailed.new("no ssh for you")) + allow(knife).to receive(:knife_ssh_with_password_auth).and_return(fallback_knife_ssh) + expect(fallback_knife_ssh).to receive(:run) knife.run end it "raises the exception if config[:ssh_password] is set and an authentication exception is raised" do knife.config[:ssh_password] = "password" - knife_ssh.should_receive(:run).and_raise(Net::SSH::AuthenticationFailed) - lambda { knife.run }.should raise_error(Net::SSH::AuthenticationFailed) + expect(knife_ssh).to receive(:run).and_raise(Net::SSH::AuthenticationFailed) + expect { knife.run }.to raise_error(Net::SSH::AuthenticationFailed) end end diff --git a/spec/unit/knife/client_bulk_delete_spec.rb b/spec/unit/knife/client_bulk_delete_spec.rb index d5cfda9885..45bb4dd16c 100644 --- a/spec/unit/knife/client_bulk_delete_spec.rb +++ b/spec/unit/knife/client_bulk_delete_spec.rb @@ -28,10 +28,10 @@ describe Chef::Knife::ClientBulkDelete do k = Chef::Knife::ClientBulkDelete.new k.name_args = name_args k.config = option_args - k.ui.stub(:stdout).and_return(stdout_io) - k.ui.stub(:stderr).and_return(stderr_io) - k.ui.stub(:confirm).and_return(knife_confirm) - k.ui.stub(:confirm_without_exit).and_return(knife_confirm) + allow(k.ui).to receive(:stdout).and_return(stdout_io) + allow(k.ui).to receive(:stderr).and_return(stderr_io) + allow(k.ui).to receive(:confirm).and_return(knife_confirm) + allow(k.ui).to receive(:confirm_without_exit).and_return(knife_confirm) k } @@ -47,7 +47,7 @@ describe Chef::Knife::ClientBulkDelete do nonvalidator_client_names.each do |client_name| client = Chef::ApiClient.new() client.name(client_name) - client.stub(:destroy).and_return(true) + allow(client).to receive(:destroy).and_return(true) clients[client_name] = client end @@ -61,8 +61,8 @@ describe Chef::Knife::ClientBulkDelete do validator_client_names.each do |validator_client_name| validator_client = Chef::ApiClient.new() validator_client.name(validator_client_name) - validator_client.stub(:validator).and_return(true) - validator_client.stub(:destroy).and_return(true) + allow(validator_client).to receive(:validator).and_return(true) + allow(validator_client).to receive(:destroy).and_return(true) clients[validator_client_name] = validator_client end @@ -75,7 +75,7 @@ describe Chef::Knife::ClientBulkDelete do } before(:each) do - Chef::ApiClient.stub(:list).and_return(clients) + allow(Chef::ApiClient).to receive(:list).and_return(clients) end describe "run" do @@ -83,44 +83,44 @@ describe Chef::Knife::ClientBulkDelete do let(:name_args) { [ ] } it "should exit if the regex is not provided" do - lambda { knife.run }.should raise_error(SystemExit) + expect { knife.run }.to raise_error(SystemExit) end end describe "with any clients" do it "should get the list of the clients" do - Chef::ApiClient.should_receive(:list) + expect(Chef::ApiClient).to receive(:list) knife.run end it "should print the name of the clients" do knife.run client_names.each do |client_name| - stdout.should include(client_name) + expect(stdout).to include(client_name) end end it "should confirm you really want to delete them" do - knife.ui.should_receive(:confirm) + expect(knife.ui).to receive(:confirm) knife.run end describe "without --delete-validators" do it "should mention that validator clients wont be deleted" do knife.run - stdout.should include("Following clients are validators and will not be deleted.") + expect(stdout).to include("Following clients are validators and will not be deleted.") info = stdout.index "Following clients are validators and will not be deleted." val = stdout.index "myorg-validator" - (val > info).should be_true + expect(val > info).to be_truthy end it "should only delete nonvalidator clients" do nonvalidator_clients.each_value do |c| - c.should_receive(:destroy) + expect(c).to receive(:destroy) end validator_clients.each_value do |c| - c.should_not_receive(:destroy) + expect(c).not_to receive(:destroy) end knife.run @@ -132,18 +132,18 @@ describe Chef::Knife::ClientBulkDelete do it "should mention that validator clients will be deleted" do knife.run - stdout.should include("The following validators will be deleted") + expect(stdout).to include("The following validators will be deleted") end it "should confirm twice" do - knife.ui.should_receive(:confirm).once - knife.ui.should_receive(:confirm_without_exit).once + expect(knife.ui).to receive(:confirm).once + expect(knife.ui).to receive(:confirm_without_exit).once knife.run end it "should delete all clients" do clients.each_value do |c| - c.should_receive(:destroy) + expect(c).to receive(:destroy) end knife.run @@ -155,10 +155,10 @@ describe Chef::Knife::ClientBulkDelete do let(:name_args) { [ "^ti" ] } it "should only delete clients that match the regex" do - clients["tim"].should_receive(:destroy) - clients["stephen"].should_not_receive(:destroy) - clients["dan"].should_not_receive(:destroy) - clients["myorg-validator"].should_not_receive(:destroy) + expect(clients["tim"]).to receive(:destroy) + expect(clients["stephen"]).not_to receive(:destroy) + expect(clients["dan"]).not_to receive(:destroy) + expect(clients["myorg-validator"]).not_to receive(:destroy) knife.run end end diff --git a/spec/unit/knife/client_create_spec.rb b/spec/unit/knife/client_create_spec.rb index 59238d69ec..8e7cc4a5e3 100644 --- a/spec/unit/knife/client_create_spec.rb +++ b/spec/unit/knife/client_create_spec.rb @@ -31,53 +31,53 @@ describe Chef::Knife::ClientCreate do } @knife.name_args = [ "adam" ] @client = Chef::ApiClient.new - @client.stub(:save).and_return({ 'private_key' => '' }) - @knife.stub(:edit_data).and_return(@client) - @knife.stub(:puts) - Chef::ApiClient.stub(:new).and_return(@client) + allow(@client).to receive(:save).and_return({ 'private_key' => '' }) + allow(@knife).to receive(:edit_data).and_return(@client) + allow(@knife).to receive(:puts) + allow(Chef::ApiClient).to receive(:new).and_return(@client) @stderr = StringIO.new - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end describe "run" do it "should create a new Client" do - Chef::ApiClient.should_receive(:new).and_return(@client) + expect(Chef::ApiClient).to receive(:new).and_return(@client) @knife.run - @stderr.string.should match /created client.+adam/i + expect(@stderr.string).to match /created client.+adam/i end it "should set the Client name" do - @client.should_receive(:name).with("adam") + expect(@client).to receive(:name).with("adam") @knife.run end it "by default it is not an admin" do - @client.should_receive(:admin).with(false) + expect(@client).to receive(:admin).with(false) @knife.run end it "by default it is not a validator" do - @client.should_receive(:validator).with(false) + expect(@client).to receive(:validator).with(false) @knife.run end it "should allow you to edit the data" do - @knife.should_receive(:edit_data).with(@client) + expect(@knife).to receive(:edit_data).with(@client) @knife.run end it "should save the Client" do - @client.should_receive(:save) + expect(@client).to receive(:save) @knife.run end describe "with -f or --file" do it "should write the private key to a file" do @knife.config[:file] = "/tmp/monkeypants" - @client.stub(:save).and_return({ 'private_key' => "woot" }) + allow(@client).to receive(:save).and_return({ 'private_key' => "woot" }) filehandle = double("Filehandle") - filehandle.should_receive(:print).with('woot') - File.should_receive(:open).with("/tmp/monkeypants", "w").and_yield(filehandle) + expect(filehandle).to receive(:print).with('woot') + expect(File).to receive(:open).with("/tmp/monkeypants", "w").and_yield(filehandle) @knife.run end end @@ -85,7 +85,7 @@ describe Chef::Knife::ClientCreate do describe "with -a or --admin" do it "should create an admin client" do @knife.config[:admin] = true - @client.should_receive(:admin).with(true) + expect(@client).to receive(:admin).with(true) @knife.run end end @@ -93,7 +93,7 @@ describe Chef::Knife::ClientCreate do describe "with --validator" do it "should create an validator client" do @knife.config[:validator] = true - @client.should_receive(:validator).with(true) + expect(@client).to receive(:validator).with(true) @knife.run end end diff --git a/spec/unit/knife/client_delete_spec.rb b/spec/unit/knife/client_delete_spec.rb index c7908a0934..0fb5e0bab7 100644 --- a/spec/unit/knife/client_delete_spec.rb +++ b/spec/unit/knife/client_delete_spec.rb @@ -30,52 +30,52 @@ describe Chef::Knife::ClientDelete do describe 'run' do it 'should delete the client' do - @knife.should_receive(:delete_object).with(Chef::ApiClient, 'adam', 'client') + expect(@knife).to receive(:delete_object).with(Chef::ApiClient, 'adam', 'client') @knife.run end it 'should print usage and exit when a client name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end describe 'with a validator' do before(:each) do - Chef::Knife::UI.stub(:confirm).and_return(true) - @knife.stub(:confirm).and_return(true) + allow(Chef::Knife::UI).to receive(:confirm).and_return(true) + allow(@knife).to receive(:confirm).and_return(true) @client = Chef::ApiClient.new - Chef::ApiClient.should_receive(:load).and_return(@client) + expect(Chef::ApiClient).to receive(:load).and_return(@client) end it 'should delete non-validator client if --delete-validators is not set' do @knife.config[:delete_validators] = false - @client.should_receive(:destroy).and_return(@client) - @knife.should_receive(:msg) + expect(@client).to receive(:destroy).and_return(@client) + expect(@knife).to receive(:msg) @knife.run end it 'should delete non-validator client if --delete-validators is set' do @knife.config[:delete_validators] = true - @client.should_receive(:destroy).and_return(@client) - @knife.should_receive(:msg) + expect(@client).to receive(:destroy).and_return(@client) + expect(@knife).to receive(:msg) @knife.run end it 'should not delete validator client if --delete-validators is not set' do @client.validator(true) - @knife.ui.should_receive(:fatal) - lambda { @knife.run}.should raise_error(SystemExit) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run}.to raise_error(SystemExit) end it 'should delete validator client if --delete-validators is set' do @knife.config[:delete_validators] = true - @client.should_receive(:destroy).and_return(@client) - @knife.should_receive(:msg) + expect(@client).to receive(:destroy).and_return(@client) + expect(@knife).to receive(:msg) @knife.run end diff --git a/spec/unit/knife/client_edit_spec.rb b/spec/unit/knife/client_edit_spec.rb index 1d7049be30..c040c5e2f2 100644 --- a/spec/unit/knife/client_edit_spec.rb +++ b/spec/unit/knife/client_edit_spec.rb @@ -26,15 +26,15 @@ describe Chef::Knife::ClientEdit do describe 'run' do it 'should edit the client' do - @knife.should_receive(:edit_object).with(Chef::ApiClient, 'adam') + expect(@knife).to receive(:edit_object).with(Chef::ApiClient, 'adam') @knife.run end it 'should print usage and exit when a client name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end end diff --git a/spec/unit/knife/client_list_spec.rb b/spec/unit/knife/client_list_spec.rb index c4834ad8d1..eff01da4e9 100644 --- a/spec/unit/knife/client_list_spec.rb +++ b/spec/unit/knife/client_list_spec.rb @@ -26,8 +26,8 @@ describe Chef::Knife::ClientList do describe 'run' do it 'should list the clients' do - Chef::ApiClient.should_receive(:list) - @knife.should_receive(:format_list_for_display) + expect(Chef::ApiClient).to receive(:list) + expect(@knife).to receive(:format_list_for_display) @knife.run end end diff --git a/spec/unit/knife/client_reregister_spec.rb b/spec/unit/knife/client_reregister_spec.rb index daf18d5d25..f1be4ed570 100644 --- a/spec/unit/knife/client_reregister_spec.rb +++ b/spec/unit/knife/client_reregister_spec.rb @@ -24,7 +24,7 @@ describe Chef::Knife::ClientReregister do @knife.name_args = [ 'adam' ] @client_mock = double('client_mock', :private_key => "foo_key") @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end context "when no client name is given on the command line" do @@ -33,29 +33,29 @@ describe Chef::Knife::ClientReregister do end it 'should print usage and exit when a client name is not provided' do - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end context 'when not configured for file output' do it 'reregisters the client and prints the key' do - Chef::ApiClient.should_receive(:reregister).with('adam').and_return(@client_mock) + expect(Chef::ApiClient).to receive(:reregister).with('adam').and_return(@client_mock) @knife.run - @stdout.string.should match( /foo_key/ ) + expect(@stdout.string).to match( /foo_key/ ) end end context 'when configured for file output' do it 'should write the private key to a file' do - Chef::ApiClient.should_receive(:reregister).with('adam').and_return(@client_mock) + expect(Chef::ApiClient).to receive(:reregister).with('adam').and_return(@client_mock) @knife.config[:file] = '/tmp/monkeypants' filehandle = StringIO.new - File.should_receive(:open).with('/tmp/monkeypants', 'w').and_yield(filehandle) + expect(File).to receive(:open).with('/tmp/monkeypants', 'w').and_yield(filehandle) @knife.run - filehandle.string.should == "foo_key" + expect(filehandle.string).to eq("foo_key") end end diff --git a/spec/unit/knife/configure_client_spec.rb b/spec/unit/knife/configure_client_spec.rb index de2a5a41e5..363743f8cc 100644 --- a/spec/unit/knife/configure_client_spec.rb +++ b/spec/unit/knife/configure_client_spec.rb @@ -26,16 +26,16 @@ describe Chef::Knife::ConfigureClient do Chef::Config[:validation_key] = '/etc/chef/validation.pem' @stderr = StringIO.new - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end describe 'run' do it 'should print usage and exit when a directory is not provided' do - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal).with(/must provide the directory/) - lambda { + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal).with(/must provide the directory/) + expect { @knife.run - }.should raise_error SystemExit + }.to raise_error SystemExit end describe 'when specifing a directory' do @@ -43,39 +43,39 @@ describe Chef::Knife::ConfigureClient do @knife.name_args = ['/home/bob/.chef'] @client_file = StringIO.new @validation_file = StringIO.new - File.should_receive(:open).with('/home/bob/.chef/client.rb', 'w'). + expect(File).to receive(:open).with('/home/bob/.chef/client.rb', 'w'). and_yield(@client_file) - File.should_receive(:open).with('/home/bob/.chef/validation.pem', 'w'). + expect(File).to receive(:open).with('/home/bob/.chef/validation.pem', 'w'). and_yield(@validation_file) - IO.should_receive(:read).and_return('foo_bar_baz') + expect(IO).to receive(:read).and_return('foo_bar_baz') end it 'should recursively create the directory' do - FileUtils.should_receive(:mkdir_p).with('/home/bob/.chef') + expect(FileUtils).to receive(:mkdir_p).with('/home/bob/.chef') @knife.run end it 'should write out the config file' do - FileUtils.stub(:mkdir_p) + allow(FileUtils).to receive(:mkdir_p) @knife.run - @client_file.string.should match /log_level\s+\:info/ - @client_file.string.should match /log_location\s+STDOUT/ - @client_file.string.should match /chef_server_url\s+'https\:\/\/chef\.example\.com'/ - @client_file.string.should match /validation_client_name\s+'chef-validator'/ + expect(@client_file.string).to match /log_level\s+\:info/ + expect(@client_file.string).to match /log_location\s+STDOUT/ + expect(@client_file.string).to match /chef_server_url\s+'https\:\/\/chef\.example\.com'/ + expect(@client_file.string).to match /validation_client_name\s+'chef-validator'/ end it 'should write out the validation.pem file' do - FileUtils.stub(:mkdir_p) + allow(FileUtils).to receive(:mkdir_p) @knife.run - @validation_file.string.should match /foo_bar_baz/ + expect(@validation_file.string).to match /foo_bar_baz/ end it 'should print information on what is being configured' do - FileUtils.stub(:mkdir_p) + allow(FileUtils).to receive(:mkdir_p) @knife.run - @stderr.string.should match /creating client configuration/i - @stderr.string.should match /writing client\.rb/i - @stderr.string.should match /writing validation\.pem/i + expect(@stderr.string).to match /creating client configuration/i + expect(@stderr.string).to match /writing client\.rb/i + expect(@stderr.string).to match /writing validation\.pem/i end end end diff --git a/spec/unit/knife/configure_spec.rb b/spec/unit/knife/configure_spec.rb index c16019dcf7..e3ea1f052c 100644 --- a/spec/unit/knife/configure_spec.rb +++ b/spec/unit/knife/configure_spec.rb @@ -7,19 +7,19 @@ describe Chef::Knife::Configure do Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::Configure.new @rest_client = double("null rest client", :post_rest => { :result => :true }) - @knife.stub(:rest).and_return(@rest_client) + allow(@knife).to receive(:rest).and_return(@rest_client) @out = StringIO.new - @knife.ui.stub(:stdout).and_return(@out) + allow(@knife.ui).to receive(:stdout).and_return(@out) @knife.config[:config_file] = '/home/you/.chef/knife.rb' @in = StringIO.new("\n" * 7) - @knife.ui.stub(:stdin).and_return(@in) + allow(@knife.ui).to receive(:stdin).and_return(@in) @err = StringIO.new - @knife.ui.stub(:stderr).and_return(@err) + allow(@knife.ui).to receive(:stderr).and_return(@err) - Ohai::System.stub(:new).and_return(ohai) + allow(Ohai::System).to receive(:new).and_return(ohai) end @@ -27,8 +27,8 @@ describe Chef::Knife::Configure do let(:ohai) do o = {} - o.stub(:require_plugin) - o.stub(:load_plugins) + allow(o).to receive(:require_plugin) + allow(o).to receive(:load_plugins) o[:fqdn] = fqdn o end @@ -44,63 +44,63 @@ describe Chef::Knife::Configure do it "asks the user for the URL of the chef server" do @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter the chef server URL: [#{default_server_url}]")) - @knife.chef_server.should == default_server_url + expect(@out.string).to match(Regexp.escape("Please enter the chef server URL: [#{default_server_url}]")) + expect(@knife.chef_server).to eq(default_server_url) end it "asks the user for the clientname they want for the new client if -i is specified" do @knife.config[:initial] = true - Etc.stub(:getlogin).and_return("a-new-user") + allow(Etc).to receive(:getlogin).and_return("a-new-user") @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter a name for the new user: [a-new-user]")) - @knife.new_client_name.should == Etc.getlogin + expect(@out.string).to match(Regexp.escape("Please enter a name for the new user: [a-new-user]")) + expect(@knife.new_client_name).to eq(Etc.getlogin) end it "should not ask the user for the clientname they want for the new client if -i and --node_name are specified" do @knife.config[:initial] = true @knife.config[:node_name] = 'testnode' - Etc.stub(:getlogin).and_return("a-new-user") + allow(Etc).to receive(:getlogin).and_return("a-new-user") @knife.ask_user_for_config - @out.string.should_not match(Regexp.escape("Please enter a name for the new user")) - @knife.new_client_name.should == 'testnode' + expect(@out.string).not_to match(Regexp.escape("Please enter a name for the new user")) + expect(@knife.new_client_name).to eq('testnode') end it "asks the user for the existing API username or clientname if -i is not specified" do - Etc.stub(:getlogin).and_return("a-new-user") + allow(Etc).to receive(:getlogin).and_return("a-new-user") @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter an existing username or clientname for the API: [a-new-user]")) - @knife.new_client_name.should == Etc.getlogin + expect(@out.string).to match(Regexp.escape("Please enter an existing username or clientname for the API: [a-new-user]")) + expect(@knife.new_client_name).to eq(Etc.getlogin) end it "asks the user for the existing admin client's name if -i is specified" do @knife.config[:initial] = true @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter the existing admin name: [admin]")) - @knife.admin_client_name.should == 'admin' + expect(@out.string).to match(Regexp.escape("Please enter the existing admin name: [admin]")) + expect(@knife.admin_client_name).to eq('admin') end it "should not ask the user for the existing admin client's name if -i and --admin-client_name are specified" do @knife.config[:initial] = true @knife.config[:admin_client_name] = 'my-webui' @knife.ask_user_for_config - @out.string.should_not match(Regexp.escape("Please enter the existing admin:")) - @knife.admin_client_name.should == 'my-webui' + expect(@out.string).not_to match(Regexp.escape("Please enter the existing admin:")) + expect(@knife.admin_client_name).to eq('my-webui') end it "should not ask the user for the existing admin client's name if -i is not specified" do @knife.ask_user_for_config - @out.string.should_not match(Regexp.escape("Please enter the existing admin: [admin]")) - @knife.admin_client_name.should_not == 'admin' + expect(@out.string).not_to match(Regexp.escape("Please enter the existing admin: [admin]")) + expect(@knife.admin_client_name).not_to eq('admin') end it "asks the user for the location of the existing admin key if -i is specified" do @knife.config[:initial] = true @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter the location of the existing admin's private key: [#{default_admin_key}]")) + expect(@out.string).to match(Regexp.escape("Please enter the location of the existing admin's private key: [#{default_admin_key}]")) if windows? - @knife.admin_client_key.capitalize.should == default_admin_key_win32.capitalize + expect(@knife.admin_client_key.capitalize).to eq(default_admin_key_win32.capitalize) else - @knife.admin_client_key.should == default_admin_key + expect(@knife.admin_client_key).to eq(default_admin_key) end end @@ -108,61 +108,61 @@ describe Chef::Knife::Configure do @knife.config[:initial] = true @knife.config[:admin_client_key] = '/home/you/.chef/my-webui.pem' @knife.ask_user_for_config - @out.string.should_not match(Regexp.escape("Please enter the location of the existing admin client's private key:")) + expect(@out.string).not_to match(Regexp.escape("Please enter the location of the existing admin client's private key:")) if windows? - @knife.admin_client_key.should match %r{^[A-Za-z]:/home/you/\.chef/my-webui\.pem$} + expect(@knife.admin_client_key).to match %r{^[A-Za-z]:/home/you/\.chef/my-webui\.pem$} else - @knife.admin_client_key.should == '/home/you/.chef/my-webui.pem' + expect(@knife.admin_client_key).to eq('/home/you/.chef/my-webui.pem') end end it "should not ask the user for the location of the existing admin key if -i is not specified" do @knife.ask_user_for_config - @out.string.should_not match(Regexp.escape("Please enter the location of the existing admin client's private key: [#{default_admin_key}]")) + expect(@out.string).not_to match(Regexp.escape("Please enter the location of the existing admin client's private key: [#{default_admin_key}]")) if windows? - @knife.admin_client_key.should_not == default_admin_key_win32 + expect(@knife.admin_client_key).not_to eq(default_admin_key_win32) else - @knife.admin_client_key.should_not == default_admin_key + expect(@knife.admin_client_key).not_to eq(default_admin_key) end end it "asks the user for the location of a chef repo" do @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter the path to a chef repository (or leave blank):")) - @knife.chef_repo.should == '' + expect(@out.string).to match(Regexp.escape("Please enter the path to a chef repository (or leave blank):")) + expect(@knife.chef_repo).to eq('') end it "asks the users for the name of the validation client" do @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter the validation clientname: [chef-validator]")) - @knife.validation_client_name.should == 'chef-validator' + expect(@out.string).to match(Regexp.escape("Please enter the validation clientname: [chef-validator]")) + expect(@knife.validation_client_name).to eq('chef-validator') end it "should not ask the users for the name of the validation client if --validation_client_name is specified" do @knife.config[:validation_client_name] = 'my-validator' @knife.ask_user_for_config - @out.string.should_not match(Regexp.escape("Please enter the validation clientname:")) - @knife.validation_client_name.should == 'my-validator' + expect(@out.string).not_to match(Regexp.escape("Please enter the validation clientname:")) + expect(@knife.validation_client_name).to eq('my-validator') end it "asks the users for the location of the validation key" do @knife.ask_user_for_config - @out.string.should match(Regexp.escape("Please enter the location of the validation key: [#{default_validator_key}]")) + expect(@out.string).to match(Regexp.escape("Please enter the location of the validation key: [#{default_validator_key}]")) if windows? - @knife.validation_key.capitalize.should == default_validator_key_win32.capitalize + expect(@knife.validation_key.capitalize).to eq(default_validator_key_win32.capitalize) else - @knife.validation_key.should == default_validator_key + expect(@knife.validation_key).to eq(default_validator_key) end end it "should not ask the users for the location of the validation key if --validation_key is specified" do @knife.config[:validation_key] = '/home/you/.chef/my-validation.pem' @knife.ask_user_for_config - @out.string.should_not match(Regexp.escape("Please enter the location of the validation key:")) + expect(@out.string).not_to match(Regexp.escape("Please enter the location of the validation key:")) if windows? - @knife.validation_key.should match %r{^[A-Za-z]:/home/you/\.chef/my-validation\.pem$} + expect(@knife.validation_key).to match %r{^[A-Za-z]:/home/you/\.chef/my-validation\.pem$} else - @knife.validation_key.should == '/home/you/.chef/my-validation.pem' + expect(@knife.validation_key).to eq('/home/you/.chef/my-validation.pem') end end @@ -176,68 +176,68 @@ describe Chef::Knife::Configure do @knife.config[:validation_key] = '/home/you/.chef/my-validation.pem' @knife.config[:repository] = '' @knife.config[:client_key] = '/home/you/a-new-user.pem' - Etc.stub(:getlogin).and_return('a-new-user') + allow(Etc).to receive(:getlogin).and_return('a-new-user') @knife.ask_user_for_config - @out.string.should match(/\s*/) + expect(@out.string).to match(/\s*/) - @knife.new_client_name.should == 'testnode' - @knife.chef_server.should == 'http://localhost:5000' - @knife.admin_client_name.should == 'my-webui' + expect(@knife.new_client_name).to eq('testnode') + expect(@knife.chef_server).to eq('http://localhost:5000') + expect(@knife.admin_client_name).to eq('my-webui') if windows? - @knife.admin_client_key.should match %r{^[A-Za-z]:/home/you/\.chef/my-webui\.pem$} - @knife.validation_key.should match %r{^[A-Za-z]:/home/you/\.chef/my-validation\.pem$} - @knife.new_client_key.should match %r{^[A-Za-z]:/home/you/a-new-user\.pem$} + expect(@knife.admin_client_key).to match %r{^[A-Za-z]:/home/you/\.chef/my-webui\.pem$} + expect(@knife.validation_key).to match %r{^[A-Za-z]:/home/you/\.chef/my-validation\.pem$} + expect(@knife.new_client_key).to match %r{^[A-Za-z]:/home/you/a-new-user\.pem$} else - @knife.admin_client_key.should == '/home/you/.chef/my-webui.pem' - @knife.validation_key.should == '/home/you/.chef/my-validation.pem' - @knife.new_client_key.should == '/home/you/a-new-user.pem' + expect(@knife.admin_client_key).to eq('/home/you/.chef/my-webui.pem') + expect(@knife.validation_key).to eq('/home/you/.chef/my-validation.pem') + expect(@knife.new_client_key).to eq('/home/you/a-new-user.pem') end - @knife.validation_client_name.should == 'my-validator' - @knife.chef_repo.should == '' + expect(@knife.validation_client_name).to eq('my-validator') + expect(@knife.chef_repo).to eq('') end it "writes the new data to a config file" do - File.stub(:expand_path).with("/home/you/.chef/knife.rb").and_return("/home/you/.chef/knife.rb") - File.stub(:expand_path).with("/home/you/.chef/#{Etc.getlogin}.pem").and_return("/home/you/.chef/#{Etc.getlogin}.pem") - File.stub(:expand_path).with(default_validator_key).and_return(default_validator_key) - File.stub(:expand_path).with(default_admin_key).and_return(default_admin_key) - FileUtils.should_receive(:mkdir_p).with("/home/you/.chef") + allow(File).to receive(:expand_path).with("/home/you/.chef/knife.rb").and_return("/home/you/.chef/knife.rb") + allow(File).to receive(:expand_path).with("/home/you/.chef/#{Etc.getlogin}.pem").and_return("/home/you/.chef/#{Etc.getlogin}.pem") + allow(File).to receive(:expand_path).with(default_validator_key).and_return(default_validator_key) + allow(File).to receive(:expand_path).with(default_admin_key).and_return(default_admin_key) + expect(FileUtils).to receive(:mkdir_p).with("/home/you/.chef") config_file = StringIO.new - ::File.should_receive(:open).with("/home/you/.chef/knife.rb", "w").and_yield config_file + expect(::File).to receive(:open).with("/home/you/.chef/knife.rb", "w").and_yield config_file @knife.config[:repository] = '/home/you/chef-repo' @knife.run - config_file.string.should match(/^node_name[\s]+'#{Etc.getlogin}'$/) - config_file.string.should match(%r{^client_key[\s]+'/home/you/.chef/#{Etc.getlogin}.pem'$}) - config_file.string.should match(/^validation_client_name\s+'chef-validator'$/) - config_file.string.should match(%r{^validation_key\s+'#{default_validator_key}'$}) - config_file.string.should match(%r{^chef_server_url\s+'#{default_server_url}'$}) - config_file.string.should match(%r{cookbook_path\s+\[ '/home/you/chef-repo/cookbooks' \]}) + expect(config_file.string).to match(/^node_name[\s]+'#{Etc.getlogin}'$/) + expect(config_file.string).to match(%r{^client_key[\s]+'/home/you/.chef/#{Etc.getlogin}.pem'$}) + expect(config_file.string).to match(/^validation_client_name\s+'chef-validator'$/) + expect(config_file.string).to match(%r{^validation_key\s+'#{default_validator_key}'$}) + expect(config_file.string).to match(%r{^chef_server_url\s+'#{default_server_url}'$}) + expect(config_file.string).to match(%r{cookbook_path\s+\[ '/home/you/chef-repo/cookbooks' \]}) end it "creates a new client when given the --initial option" do - File.should_receive(:expand_path).with("/home/you/.chef/knife.rb").and_return("/home/you/.chef/knife.rb") - File.should_receive(:expand_path).with("/home/you/.chef/a-new-user.pem").and_return("/home/you/.chef/a-new-user.pem") - File.should_receive(:expand_path).with(default_validator_key).and_return(default_validator_key) - File.should_receive(:expand_path).with(default_admin_key).and_return(default_admin_key) + expect(File).to receive(:expand_path).with("/home/you/.chef/knife.rb").and_return("/home/you/.chef/knife.rb") + expect(File).to receive(:expand_path).with("/home/you/.chef/a-new-user.pem").and_return("/home/you/.chef/a-new-user.pem") + expect(File).to receive(:expand_path).with(default_validator_key).and_return(default_validator_key) + expect(File).to receive(:expand_path).with(default_admin_key).and_return(default_admin_key) Chef::Config[:node_name] = "webmonkey.example.com" user_command = Chef::Knife::UserCreate.new - user_command.should_receive(:run) + expect(user_command).to receive(:run) - Etc.stub(:getlogin).and_return("a-new-user") + allow(Etc).to receive(:getlogin).and_return("a-new-user") - Chef::Knife::UserCreate.stub(:new).and_return(user_command) - FileUtils.should_receive(:mkdir_p).with("/home/you/.chef") - ::File.should_receive(:open).with("/home/you/.chef/knife.rb", "w") + allow(Chef::Knife::UserCreate).to receive(:new).and_return(user_command) + expect(FileUtils).to receive(:mkdir_p).with("/home/you/.chef") + expect(::File).to receive(:open).with("/home/you/.chef/knife.rb", "w") @knife.config[:initial] = true @knife.config[:user_password] = "blah" @knife.run - user_command.name_args.should == Array("a-new-user") - user_command.config[:user_password].should == "blah" - user_command.config[:admin].should be_true - user_command.config[:file].should == "/home/you/.chef/a-new-user.pem" - user_command.config[:yes].should be_true - user_command.config[:disable_editing].should be_true + expect(user_command.name_args).to eq(Array("a-new-user")) + expect(user_command.config[:user_password]).to eq("blah") + expect(user_command.config[:admin]).to be_truthy + expect(user_command.config[:file]).to eq("/home/you/.chef/a-new-user.pem") + expect(user_command.config[:yes]).to be_truthy + expect(user_command.config[:disable_editing]).to be_truthy end end diff --git a/spec/unit/knife/cookbook_bulk_delete_spec.rb b/spec/unit/knife/cookbook_bulk_delete_spec.rb index fb4b1d1484..98cd06bbbc 100644 --- a/spec/unit/knife/cookbook_bulk_delete_spec.rb +++ b/spec/unit/knife/cookbook_bulk_delete_spec.rb @@ -28,19 +28,19 @@ describe Chef::Knife::CookbookBulkDelete do @knife.name_args = ["."] @stdout = StringIO.new @stderr = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:stderr).and_return(@stderr) - @knife.ui.stub(:confirm).and_return(true) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:confirm).and_return(true) @cookbooks = Hash.new %w{cheezburger pizza lasagna}.each do |cookbook_name| cookbook = Chef::CookbookVersion.new(cookbook_name) @cookbooks[cookbook_name] = cookbook end @rest = double("Chef::REST") - @rest.stub(:get_rest).and_return(@cookbooks) - @rest.stub(:delete_rest).and_return(true) - @knife.stub(:rest).and_return(@rest) - Chef::CookbookVersion.stub(:list).and_return(@cookbooks) + allow(@rest).to receive(:get_rest).and_return(@cookbooks) + allow(@rest).to receive(:delete_rest).and_return(true) + allow(@knife).to receive(:rest).and_return(@rest) + allow(Chef::CookbookVersion).to receive(:list).and_return(@cookbooks) end @@ -49,41 +49,41 @@ describe Chef::Knife::CookbookBulkDelete do describe "when there are several cookbooks on the server" do before do @cheezburger = {'cheezburger' => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-cheez", "version" => "1.0.0"}]}} - @rest.stub(:get_rest).with('cookbooks/cheezburger').and_return(@cheezburger) + allow(@rest).to receive(:get_rest).with('cookbooks/cheezburger').and_return(@cheezburger) @pizza = {'pizza' => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-pizza", "version" => "2.0.0"}]}} - @rest.stub(:get_rest).with('cookbooks/pizza').and_return(@pizza) + allow(@rest).to receive(:get_rest).with('cookbooks/pizza').and_return(@pizza) @lasagna = {'lasagna' => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-lasagna", "version" => "3.0.0"}]}} - @rest.stub(:get_rest).with('cookbooks/lasagna').and_return(@lasagna) + allow(@rest).to receive(:get_rest).with('cookbooks/lasagna').and_return(@lasagna) end it "should print the cookbooks you are about to delete" do expected = @knife.ui.list(@cookbooks.keys.sort, :columns_down) @knife.run - @stdout.string.should match(/#{expected}/) + expect(@stdout.string).to match(/#{expected}/) end it "should confirm you really want to delete them" do - @knife.ui.should_receive(:confirm) + expect(@knife.ui).to receive(:confirm) @knife.run end it "should delete each cookbook" do {"cheezburger" => "1.0.0", "pizza" => "2.0.0", "lasagna" => '3.0.0'}.each do |cookbook_name, version| - @rest.should_receive(:delete_rest).with("cookbooks/#{cookbook_name}/#{version}") + expect(@rest).to receive(:delete_rest).with("cookbooks/#{cookbook_name}/#{version}") end @knife.run end it "should only delete cookbooks that match the regex" do @knife.name_args = ["cheezburger"] - @rest.should_receive(:delete_rest).with('cookbooks/cheezburger/1.0.0') + expect(@rest).to receive(:delete_rest).with('cookbooks/cheezburger/1.0.0') @knife.run end end it "should exit if the regex is not provided" do @knife.name_args = [] - lambda { @knife.run }.should raise_error(SystemExit) + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/cookbook_create_spec.rb b/spec/unit/knife/cookbook_create_spec.rb index 06475d3ac9..3354432d39 100644 --- a/spec/unit/knife/cookbook_create_spec.rb +++ b/spec/unit/knife/cookbook_create_spec.rb @@ -26,29 +26,29 @@ describe Chef::Knife::CookbookCreate do @knife.config = {} @knife.name_args = ["foobar"] @stdout = StringIO.new - @knife.stub(:stdout).and_return(@stdout) + allow(@knife).to receive(:stdout).and_return(@stdout) end describe "run" do # Fixes CHEF-2579 it "should expand the path of the cookbook directory" do - File.should_receive(:expand_path).with("~/tmp/monkeypants") + expect(File).to receive(:expand_path).with("~/tmp/monkeypants") @knife.config = {:cookbook_path => "~/tmp/monkeypants"} - @knife.stub(:create_cookbook) - @knife.stub(:create_readme) - @knife.stub(:create_changelog) - @knife.stub(:create_metadata) + allow(@knife).to receive(:create_cookbook) + allow(@knife).to receive(:create_readme) + allow(@knife).to receive(:create_changelog) + allow(@knife).to receive(:create_metadata) @knife.run end it "should create a new cookbook with default values to copyright name, email, readme format and license if those are not supplied" do @dir = Dir.tmpdir @knife.config = {:cookbook_path => @dir} - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "YOUR_COMPANY_NAME", "none") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "YOUR_COMPANY_NAME", "YOUR_EMAIL", "none", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "YOUR_COMPANY_NAME", "none") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "YOUR_COMPANY_NAME", "YOUR_EMAIL", "none", "md") @knife.run end @@ -59,10 +59,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_copyright => "Opscode, Inc" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "YOUR_EMAIL", "none", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "YOUR_EMAIL", "none", "md") @knife.run end @@ -74,10 +74,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_email => "nuo@opscode.com" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "none", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "none", "md") @knife.run end @@ -90,10 +90,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "apachev2" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "apachev2") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "apachev2", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "apachev2") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "apachev2", "md") @knife.run end @@ -106,10 +106,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => false } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "none", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "none", "md") @knife.run end @@ -122,10 +122,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "false" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "none", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "none") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "none", "md") @knife.run end @@ -138,10 +138,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "gplv2" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "gplv2") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "gplv2", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "gplv2") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "gplv2", "md") @knife.run end @@ -154,10 +154,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "gplv3" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "gplv3") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "gplv3", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "gplv3") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "gplv3", "md") @knife.run end @@ -170,10 +170,10 @@ describe Chef::Knife::CookbookCreate do :cookbook_license => "mit" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "md") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "md") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "md") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "md") @knife.run end @@ -187,10 +187,10 @@ describe Chef::Knife::CookbookCreate do :readme_format => "rdoc" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "rdoc") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "rdoc") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "rdoc") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "rdoc") @knife.run end @@ -204,10 +204,10 @@ describe Chef::Knife::CookbookCreate do :readme_format => "mkd" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "mkd") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "mkd") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "mkd") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "mkd") @knife.run end @@ -221,10 +221,10 @@ describe Chef::Knife::CookbookCreate do :readme_format => "txt" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "txt") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "txt") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "txt") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "txt") @knife.run end @@ -238,10 +238,10 @@ describe Chef::Knife::CookbookCreate do :readme_format => "foo" } @knife.name_args=["foobar"] - @knife.should_receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") - @knife.should_receive(:create_readme).with(@dir, @knife.name_args.first, "foo") - @knife.should_receive(:create_changelog).with(@dir, @knife.name_args.first) - @knife.should_receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "foo") + expect(@knife).to receive(:create_cookbook).with(@dir, @knife.name_args.first, "Opscode, Inc", "mit") + expect(@knife).to receive(:create_readme).with(@dir, @knife.name_args.first, "foo") + expect(@knife).to receive(:create_changelog).with(@dir, @knife.name_args.first) + expect(@knife).to receive(:create_metadata).with(@dir, @knife.name_args.first, "Opscode, Inc", "nuo@opscode.com", "mit", "foo") @knife.run end @@ -252,7 +252,7 @@ describe Chef::Knife::CookbookCreate do it "should throw an argument error" do @dir = Dir.tmpdir - lambda{@knife.run}.should raise_error(ArgumentError) + expect{@knife.run}.to raise_error(ArgumentError) end end diff --git a/spec/unit/knife/cookbook_delete_spec.rb b/spec/unit/knife/cookbook_delete_spec.rb index 53b120be71..4e75a689e3 100644 --- a/spec/unit/knife/cookbook_delete_spec.rb +++ b/spec/unit/knife/cookbook_delete_spec.rb @@ -24,29 +24,29 @@ describe Chef::Knife::CookbookDelete do @knife.name_args = ['foobar'] @knife.cookbook_name = 'foobar' @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) @stderr = StringIO.new - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end describe 'run' do it 'should print usage and exit when a cookbook name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end describe 'when specifying a cookbook name' do it 'should delete the cookbook without a specific version' do - @knife.should_receive(:delete_without_explicit_version) + expect(@knife).to receive(:delete_without_explicit_version) @knife.run end describe 'and a version' do it 'should delete the specific version of the cookbook' do @knife.name_args << '1.0.0' - @knife.should_receive(:delete_explicit_version) + expect(@knife).to receive(:delete_explicit_version) @knife.run end end @@ -54,7 +54,7 @@ describe Chef::Knife::CookbookDelete do describe 'with -a or --all' do it 'should delete all versions of the cookbook' do @knife.config[:all] = true - @knife.should_receive(:delete_all_versions) + expect(@knife).to receive(:delete_all_versions) @knife.run end end @@ -62,9 +62,9 @@ describe Chef::Knife::CookbookDelete do describe 'with -p or --purge' do it 'should prompt to purge the files' do @knife.config[:purge] = true - @knife.should_receive(:confirm). + expect(@knife).to receive(:confirm). with(/.+Are you sure you want to purge files.+/) - @knife.should_receive(:delete_without_explicit_version) + expect(@knife).to receive(:delete_without_explicit_version) @knife.run end end @@ -75,10 +75,10 @@ describe Chef::Knife::CookbookDelete do it 'should delete the specific cookbook version' do @knife.cookbook_name = 'foobar' @knife.version = '1.0.0' - @knife.should_receive(:delete_object).with(Chef::CookbookVersion, + expect(@knife).to receive(:delete_object).with(Chef::CookbookVersion, 'foobar version 1.0.0', 'cookbook').and_yield() - @knife.should_receive(:delete_request).with('cookbooks/foobar/1.0.0') + expect(@knife).to receive(:delete_request).with('cookbooks/foobar/1.0.0') @knife.delete_explicit_version end end @@ -86,8 +86,8 @@ describe Chef::Knife::CookbookDelete do describe 'delete_all_versions' do it 'should prompt to delete all versions of the cookbook' do @knife.cookbook_name = 'foobar' - @knife.should_receive(:confirm).with('Do you really want to delete all versions of foobar') - @knife.should_receive(:delete_all_without_confirmation) + expect(@knife).to receive(:confirm).with('Do you really want to delete all versions of foobar') + expect(@knife).to receive(:delete_all_without_confirmation) @knife.delete_all_versions end end @@ -95,9 +95,9 @@ describe Chef::Knife::CookbookDelete do describe 'delete_all_without_confirmation' do it 'should delete all versions without confirmation' do versions = ['1.0.0', '1.1.0'] - @knife.should_receive(:available_versions).and_return(versions) + expect(@knife).to receive(:available_versions).and_return(versions) versions.each do |v| - @knife.should_receive(:delete_version_without_confirmation).with(v) + expect(@knife).to receive(:delete_version_without_confirmation).with(v) end @knife.delete_all_without_confirmation end @@ -105,20 +105,20 @@ describe Chef::Knife::CookbookDelete do describe 'delete_without_explicit_version' do it 'should exit if there are no available versions' do - @knife.should_receive(:available_versions).and_return(nil) - lambda { @knife.delete_without_explicit_version }.should raise_error(SystemExit) + expect(@knife).to receive(:available_versions).and_return(nil) + expect { @knife.delete_without_explicit_version }.to raise_error(SystemExit) end it 'should delete the version if only one is found' do - @knife.should_receive(:available_versions).at_least(:once).and_return(['1.0.0']) - @knife.should_receive(:delete_explicit_version) + expect(@knife).to receive(:available_versions).at_least(:once).and_return(['1.0.0']) + expect(@knife).to receive(:delete_explicit_version) @knife.delete_without_explicit_version end it 'should ask which version(s) to delete if multiple are found' do - @knife.should_receive(:available_versions).at_least(:once).and_return(['1.0.0', '1.1.0']) - @knife.should_receive(:ask_which_versions_to_delete).and_return(['1.0.0', '1.1.0']) - @knife.should_receive(:delete_versions_without_confirmation).with(['1.0.0', '1.1.0']) + expect(@knife).to receive(:available_versions).at_least(:once).and_return(['1.0.0', '1.1.0']) + expect(@knife).to receive(:ask_which_versions_to_delete).and_return(['1.0.0', '1.1.0']) + expect(@knife).to receive(:delete_versions_without_confirmation).with(['1.0.0', '1.1.0']) @knife.delete_without_explicit_version end end @@ -126,7 +126,7 @@ describe Chef::Knife::CookbookDelete do describe 'available_versions' do before(:each) do @rest_mock = double('rest') - @knife.should_receive(:rest).and_return(@rest_mock) + expect(@knife).to receive(:rest).and_return(@rest_mock) @cookbook_data = { 'foobar' => { 'versions' => [{'version' => '1.0.0'}, {'version' => '1.1.0'}, {'version' => '2.0.0'} ]} @@ -134,85 +134,85 @@ describe Chef::Knife::CookbookDelete do end it 'should return the list of versions of the cookbook' do - @rest_mock.should_receive(:get_rest).with('cookbooks/foobar').and_return(@cookbook_data) - @knife.available_versions.should == ['1.0.0', '1.1.0', '2.0.0'] + expect(@rest_mock).to receive(:get_rest).with('cookbooks/foobar').and_return(@cookbook_data) + expect(@knife.available_versions).to eq(['1.0.0', '1.1.0', '2.0.0']) end it 'should raise if an error other than HTTP 404 is returned' do exception = Net::HTTPServerException.new('500 Internal Server Error', '500') - @rest_mock.should_receive(:get_rest).and_raise(exception) - lambda { @knife.available_versions }.should raise_error Net::HTTPServerException + expect(@rest_mock).to receive(:get_rest).and_raise(exception) + expect { @knife.available_versions }.to raise_error Net::HTTPServerException end describe "if the cookbook can't be found" do before(:each) do - @rest_mock.should_receive(:get_rest). + expect(@rest_mock).to receive(:get_rest). and_raise(Net::HTTPServerException.new('404 Not Found', '404')) end it 'should print an error' do @knife.available_versions - @stderr.string.should match /error.+cannot find a cookbook named foobar/i + expect(@stderr.string).to match /error.+cannot find a cookbook named foobar/i end it 'should return nil' do - @knife.available_versions.should == nil + expect(@knife.available_versions).to eq(nil) end end end describe 'ask_which_version_to_delete' do before(:each) do - @knife.stub(:available_versions).and_return(['1.0.0', '1.1.0', '2.0.0']) + allow(@knife).to receive(:available_versions).and_return(['1.0.0', '1.1.0', '2.0.0']) end it 'should prompt the user to select a version' do prompt = /Which version\(s\) do you want to delete\?.+1\. foobar 1\.0\.0.+2\. foobar 1\.1\.0.+3\. foobar 2\.0\.0.+4\. All versions.+/m - @knife.should_receive(:ask_question).with(prompt).and_return('1') + expect(@knife).to receive(:ask_question).with(prompt).and_return('1') @knife.ask_which_versions_to_delete end it "should print an error and exit if a version wasn't specified" do - @knife.should_receive(:ask_question).and_return('') - @knife.ui.should_receive(:error).with(/no versions specified/i) - lambda { @knife.ask_which_versions_to_delete }.should raise_error(SystemExit) + expect(@knife).to receive(:ask_question).and_return('') + expect(@knife.ui).to receive(:error).with(/no versions specified/i) + expect { @knife.ask_which_versions_to_delete }.to raise_error(SystemExit) end it 'should print an error if an invalid choice was selected' do - @knife.should_receive(:ask_question).and_return('100') - @knife.ui.should_receive(:error).with(/100 is not a valid choice/i) + expect(@knife).to receive(:ask_question).and_return('100') + expect(@knife.ui).to receive(:error).with(/100 is not a valid choice/i) @knife.ask_which_versions_to_delete end it 'should return the selected versions' do - @knife.should_receive(:ask_question).and_return('1, 3') - @knife.ask_which_versions_to_delete.should == ['1.0.0', '2.0.0'] + expect(@knife).to receive(:ask_question).and_return('1, 3') + expect(@knife.ask_which_versions_to_delete).to eq(['1.0.0', '2.0.0']) end it "should return all of the versions if 'all' was selected" do - @knife.should_receive(:ask_question).and_return('4') - @knife.ask_which_versions_to_delete.should == [:all] + expect(@knife).to receive(:ask_question).and_return('4') + expect(@knife.ask_which_versions_to_delete).to eq([:all]) end end describe 'delete_version_without_confirmation' do it 'should delete the cookbook version' do - @knife.should_receive(:delete_request).with('cookbooks/foobar/1.0.0') + expect(@knife).to receive(:delete_request).with('cookbooks/foobar/1.0.0') @knife.delete_version_without_confirmation('1.0.0') end it 'should output that the cookbook was deleted' do - @knife.stub(:delete_request) + allow(@knife).to receive(:delete_request) @knife.delete_version_without_confirmation('1.0.0') - @stderr.string.should match /deleted cookbook\[foobar\]\[1.0.0\]/im + expect(@stderr.string).to match /deleted cookbook\[foobar\]\[1.0.0\]/im end describe 'with --print-after' do it 'should display the cookbook data' do object = '' @knife.config[:print_after] = true - @knife.stub(:delete_request).and_return(object) - @knife.should_receive(:format_for_display).with(object) + allow(@knife).to receive(:delete_request).and_return(object) + expect(@knife).to receive(:format_for_display).with(object) @knife.delete_version_without_confirmation('1.0.0') end end @@ -222,7 +222,7 @@ describe Chef::Knife::CookbookDelete do it 'should delete each version without confirmation' do versions = ['1.0.0', '1.1.0'] versions.each do |v| - @knife.should_receive(:delete_version_without_confirmation).with(v) + expect(@knife).to receive(:delete_version_without_confirmation).with(v) end @knife.delete_versions_without_confirmation(versions) end @@ -230,7 +230,7 @@ describe Chef::Knife::CookbookDelete do describe 'with -a or --all' do it 'should delete all versions without confirmation' do versions = [:all] - @knife.should_receive(:delete_all_without_confirmation) + expect(@knife).to receive(:delete_all_without_confirmation) @knife.delete_versions_without_confirmation(versions) end end diff --git a/spec/unit/knife/cookbook_download_spec.rb b/spec/unit/knife/cookbook_download_spec.rb index 6f40a3396b..7ca1adfcb5 100644 --- a/spec/unit/knife/cookbook_download_spec.rb +++ b/spec/unit/knife/cookbook_download_spec.rb @@ -22,22 +22,22 @@ describe Chef::Knife::CookbookDownload do before(:each) do @knife = Chef::Knife::CookbookDownload.new @stderr = StringIO.new - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end describe 'run' do it 'should print usage and exit when a cookbook name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal).with(/must specify a cookbook name/) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal).with(/must specify a cookbook name/) + expect { @knife.run }.to raise_error(SystemExit) end it 'should exit with a fatal error when there is no cookbook on the server' do @knife.name_args = ['foobar', nil] - @knife.should_receive(:determine_version).and_return(nil) - @knife.ui.should_receive(:fatal).with('No such cookbook found') - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:determine_version).and_return(nil) + expect(@knife.ui).to receive(:fatal).with('No such cookbook found') + expect { @knife.run }.to raise_error(SystemExit) end describe 'with a cookbook name' do @@ -45,7 +45,7 @@ describe Chef::Knife::CookbookDownload do @knife.name_args = ['foobar'] @knife.config[:download_directory] = '/var/tmp/chef' @rest_mock = double('rest') - @knife.stub(:rest).and_return(@rest_mock) + allow(@knife).to receive(:rest).and_return(@rest_mock) @manifest_data = { :recipes => [ @@ -67,17 +67,17 @@ describe Chef::Knife::CookbookDownload do } @cookbook_mock = double('cookbook') - @cookbook_mock.stub(:version).and_return('1.0.0') - @cookbook_mock.stub(:manifest).and_return(@manifest_data) - @rest_mock.should_receive(:get_rest).with('cookbooks/foobar/1.0.0'). + allow(@cookbook_mock).to receive(:version).and_return('1.0.0') + allow(@cookbook_mock).to receive(:manifest).and_return(@manifest_data) + expect(@rest_mock).to receive(:get_rest).with('cookbooks/foobar/1.0.0'). and_return(@cookbook_mock) end it 'should determine which version if one was not explicitly specified'do - @cookbook_mock.stub(:manifest).and_return({}) - @knife.should_receive(:determine_version).and_return('1.0.0') - File.should_receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(false) - Chef::CookbookVersion.stub(:COOKBOOK_SEGEMENTS).and_return([]) + allow(@cookbook_mock).to receive(:manifest).and_return({}) + expect(@knife).to receive(:determine_version).and_return('1.0.0') + expect(File).to receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(false) + allow(Chef::CookbookVersion).to receive(:COOKBOOK_SEGEMENTS).and_return([]) @knife.run end @@ -88,50 +88,50 @@ describe Chef::Knife::CookbookDownload do @files_mocks = {} @files.map { |f| File.basename(f) }.flatten.uniq.each do |f| @files_mocks[f] = double("#{f}_mock") - @files_mocks[f].stub(:path).and_return("/var/tmp/#{f}") + allow(@files_mocks[f]).to receive(:path).and_return("/var/tmp/#{f}") end end it 'should print an error and exit if the cookbook download directory already exists' do - File.should_receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(true) - @knife.ui.should_receive(:fatal).with(/\/var\/tmp\/chef\/foobar-1\.0\.0 exists/i) - lambda { @knife.run }.should raise_error(SystemExit) + expect(File).to receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(true) + expect(@knife.ui).to receive(:fatal).with(/\/var\/tmp\/chef\/foobar-1\.0\.0 exists/i) + expect { @knife.run }.to raise_error(SystemExit) end describe 'when downloading the cookbook' do before(:each) do @files.map { |f| File.dirname(f) }.flatten.uniq.each do |dir| - FileUtils.should_receive(:mkdir_p).with("/var/tmp/chef/foobar-1.0.0/#{dir}"). + expect(FileUtils).to receive(:mkdir_p).with("/var/tmp/chef/foobar-1.0.0/#{dir}"). at_least(:once) end @files_mocks.each_pair do |file, mock| - @rest_mock.should_receive(:get_rest).with("http://example.org/files/#{file}", true). + expect(@rest_mock).to receive(:get_rest).with("http://example.org/files/#{file}", true). and_return(mock) end - @rest_mock.should_receive(:sign_on_redirect=).with(false).at_least(:once) + expect(@rest_mock).to receive(:sign_on_redirect=).with(false).at_least(:once) @files.each do |f| - FileUtils.should_receive(:mv). + expect(FileUtils).to receive(:mv). with("/var/tmp/#{File.basename(f)}", "/var/tmp/chef/foobar-1.0.0/#{f}") end end it "should download the cookbook when the cookbook download directory doesn't exist" do - File.should_receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(false) + expect(File).to receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(false) @knife.run ['attributes', 'recipes', 'templates'].each do |segment| - @stderr.string.should match /downloading #{segment}/im + expect(@stderr.string).to match /downloading #{segment}/im end - @stderr.string.should match /downloading foobar cookbook version 1\.0\.0/im - @stderr.string.should match /cookbook downloaded to \/var\/tmp\/chef\/foobar-1\.0\.0/im + expect(@stderr.string).to match /downloading foobar cookbook version 1\.0\.0/im + expect(@stderr.string).to match /cookbook downloaded to \/var\/tmp\/chef\/foobar-1\.0\.0/im end describe 'with -f or --force' do it 'should remove the existing the cookbook download directory if it exists' do @knife.config[:force] = true - File.should_receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(true) - FileUtils.should_receive(:rm_rf).with('/var/tmp/chef/foobar-1.0.0') + expect(File).to receive(:exists?).with('/var/tmp/chef/foobar-1.0.0').and_return(true) + expect(FileUtils).to receive(:rm_rf).with('/var/tmp/chef/foobar-1.0.0') @knife.run end end @@ -145,30 +145,30 @@ describe Chef::Knife::CookbookDownload do describe 'determine_version' do it 'should return nil if there are no versions' do - @knife.should_receive(:available_versions).and_return(nil) - @knife.determine_version.should == nil - @knife.version.should == nil + expect(@knife).to receive(:available_versions).and_return(nil) + expect(@knife.determine_version).to eq(nil) + expect(@knife.version).to eq(nil) end it 'should return and set the version if there is only one version' do - @knife.should_receive(:available_versions).at_least(:once).and_return(['1.0.0']) - @knife.determine_version.should == '1.0.0' - @knife.version.should == '1.0.0' + expect(@knife).to receive(:available_versions).at_least(:once).and_return(['1.0.0']) + expect(@knife.determine_version).to eq('1.0.0') + expect(@knife.version).to eq('1.0.0') end it 'should ask which version to download and return it if there is more than one' do - @knife.should_receive(:available_versions).at_least(:once).and_return(['1.0.0', '2.0.0']) - @knife.should_receive(:ask_which_version).and_return('1.0.0') - @knife.determine_version.should == '1.0.0' + expect(@knife).to receive(:available_versions).at_least(:once).and_return(['1.0.0', '2.0.0']) + expect(@knife).to receive(:ask_which_version).and_return('1.0.0') + expect(@knife.determine_version).to eq('1.0.0') end describe 'with -N or --latest' do it 'should return and set the version to the latest version' do @knife.config[:latest] = true - @knife.should_receive(:available_versions).at_least(:once). + expect(@knife).to receive(:available_versions).at_least(:once). and_return(['1.0.0', '1.1.0', '2.0.0']) @knife.determine_version - @knife.version.to_s.should == '2.0.0' + expect(@knife.version.to_s).to eq('2.0.0') end end end @@ -179,23 +179,23 @@ describe Chef::Knife::CookbookDownload do end it 'should return nil if there are no versions' do - Chef::CookbookVersion.should_receive(:available_versions). + expect(Chef::CookbookVersion).to receive(:available_versions). with('foobar'). and_return(nil) - @knife.available_versions.should == nil + expect(@knife.available_versions).to eq(nil) end it 'should return the available versions' do - Chef::CookbookVersion.should_receive(:available_versions). + expect(Chef::CookbookVersion).to receive(:available_versions). with('foobar'). and_return(['1.1.0', '2.0.0', '1.0.0']) - @knife.available_versions.should == [Chef::Version.new('1.0.0'), + expect(@knife.available_versions).to eq([Chef::Version.new('1.0.0'), Chef::Version.new('1.1.0'), - Chef::Version.new('2.0.0')] + Chef::Version.new('2.0.0')]) end it 'should avoid multiple API calls to the server' do - Chef::CookbookVersion.should_receive(:available_versions). + expect(Chef::CookbookVersion).to receive(:available_versions). once. with('foobar'). and_return(['1.1.0', '2.0.0', '1.0.0']) @@ -207,31 +207,31 @@ describe Chef::Knife::CookbookDownload do describe 'ask_which_version' do before(:each) do @knife.cookbook_name = 'foobar' - @knife.stub(:available_versions).and_return(['1.0.0', '1.1.0', '2.0.0']) + allow(@knife).to receive(:available_versions).and_return(['1.0.0', '1.1.0', '2.0.0']) end it 'should prompt the user to select a version' do prompt = /Which version do you want to download\?.+1\. foobar 1\.0\.0.+2\. foobar 1\.1\.0.+3\. foobar 2\.0\.0.+/m - @knife.should_receive(:ask_question).with(prompt).and_return('1') + expect(@knife).to receive(:ask_question).with(prompt).and_return('1') @knife.ask_which_version end it "should set the version to the user's selection" do - @knife.should_receive(:ask_question).and_return('1') + expect(@knife).to receive(:ask_question).and_return('1') @knife.ask_which_version - @knife.version.should == '1.0.0' + expect(@knife.version).to eq('1.0.0') end it "should print an error and exit if a version wasn't specified" do - @knife.should_receive(:ask_question).and_return('') - @knife.ui.should_receive(:error).with(/is not a valid value/i) - lambda { @knife.ask_which_version }.should raise_error(SystemExit) + expect(@knife).to receive(:ask_question).and_return('') + expect(@knife.ui).to receive(:error).with(/is not a valid value/i) + expect { @knife.ask_which_version }.to raise_error(SystemExit) end it 'should print an error if an invalid choice was selected' do - @knife.should_receive(:ask_question).and_return('100') - @knife.ui.should_receive(:error).with(/'100' is not a valid value/i) - lambda { @knife.ask_which_version }.should raise_error(SystemExit) + expect(@knife).to receive(:ask_question).and_return('100') + expect(@knife.ui).to receive(:error).with(/'100' is not a valid value/i) + expect { @knife.ask_which_version }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/cookbook_list_spec.rb b/spec/unit/knife/cookbook_list_spec.rb index 9ff16edb37..559f700bb4 100644 --- a/spec/unit/knife/cookbook_list_spec.rb +++ b/spec/unit/knife/cookbook_list_spec.rb @@ -22,7 +22,7 @@ describe Chef::Knife::CookbookList do before do @knife = Chef::Knife::CookbookList.new @rest_mock = double('rest') - @knife.stub(:rest).and_return(@rest_mock) + allow(@knife).to receive(:rest).and_return(@rest_mock) @cookbook_names = ['apache2', 'mysql'] @base_url = 'https://server.example.com/cookbooks' @cookbook_data = {} @@ -32,22 +32,22 @@ describe Chef::Knife::CookbookList do 'url' => "#{@base_url}/#{item}/1.0.1"}]} end @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe 'run' do it 'should display the latest version of the cookbooks' do - @rest_mock.should_receive(:get_rest).with('/cookbooks?num_versions=1'). + expect(@rest_mock).to receive(:get_rest).with('/cookbooks?num_versions=1'). and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| - @stdout.string.should match /#{item}\s+1\.0\.1/ + expect(@stdout.string).to match /#{item}\s+1\.0\.1/ end end it 'should query cookbooks for the configured environment' do @knife.config[:environment] = 'production' - @rest_mock.should_receive(:get_rest). + expect(@rest_mock).to receive(:get_rest). with('/environments/production/cookbooks?num_versions=1'). and_return(@cookbook_data) @knife.run @@ -56,11 +56,11 @@ describe Chef::Knife::CookbookList do describe 'with -w or --with-uri' do it 'should display the cookbook uris' do @knife.config[:with_uri] = true - @rest_mock.stub(:get_rest).and_return(@cookbook_data) + allow(@rest_mock).to receive(:get_rest).and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| pattern = /#{Regexp.escape(@cookbook_data[item]['versions'].first['url'])}/ - @stdout.string.should match pattern + expect(@stdout.string).to match pattern end end end @@ -75,11 +75,11 @@ describe Chef::Knife::CookbookList do it 'should display all versions of the cookbooks' do @knife.config[:all_versions] = true - @rest_mock.should_receive(:get_rest).with('/cookbooks?num_versions=all'). + expect(@rest_mock).to receive(:get_rest).with('/cookbooks?num_versions=all'). and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| - @stdout.string.should match /#{item}\s+1\.0\.1\s+1\.0\.0/ + expect(@stdout.string).to match /#{item}\s+1\.0\.1\s+1\.0\.0/ end end end diff --git a/spec/unit/knife/cookbook_metadata_from_file_spec.rb b/spec/unit/knife/cookbook_metadata_from_file_spec.rb index 68ab6740ab..456e378ca2 100644 --- a/spec/unit/knife/cookbook_metadata_from_file_spec.rb +++ b/spec/unit/knife/cookbook_metadata_from_file_spec.rb @@ -27,10 +27,10 @@ describe Chef::Knife::CookbookMetadataFromFile do @tgt = File.expand_path(File.join(CHEF_SPEC_DATA, "metadata", "quick_start", "metadata.json")) @knife = Chef::Knife::CookbookMetadataFromFile.new @knife.name_args = [ @src ] - @knife.stub(:to_json_pretty).and_return(true) + allow(@knife).to receive(:to_json_pretty).and_return(true) @md = Chef::Cookbook::Metadata.new - Chef::Cookbook::Metadata.stub(:new).and_return(@md) - $stdout.stub(:write) + allow(Chef::Cookbook::Metadata).to receive(:new).and_return(@md) + allow($stdout).to receive(:write) end after do @@ -41,23 +41,23 @@ describe Chef::Knife::CookbookMetadataFromFile do describe "run" do it "should determine cookbook name from path" do - @md.should_receive(:name).with() - @md.should_receive(:name).with("quick_start") + expect(@md).to receive(:name).with(no_args) + expect(@md).to receive(:name).with("quick_start") @knife.run end it "should load the metadata source" do - @md.should_receive(:from_file).with(@src) + expect(@md).to receive(:from_file).with(@src) @knife.run end it "should write out the metadata to the correct location" do - File.should_receive(:open).with(@tgt, "w") + expect(File).to receive(:open).with(@tgt, "w") @knife.run end it "should generate json from the metadata" do - Chef::JSONCompat.should_receive(:to_json_pretty).with(@md) + expect(Chef::JSONCompat).to receive(:to_json_pretty).with(@md) @knife.run end diff --git a/spec/unit/knife/cookbook_metadata_spec.rb b/spec/unit/knife/cookbook_metadata_spec.rb index 1d6568739c..861d85f1f7 100644 --- a/spec/unit/knife/cookbook_metadata_spec.rb +++ b/spec/unit/knife/cookbook_metadata_spec.rb @@ -26,25 +26,25 @@ describe Chef::Knife::CookbookMetadata do @json_data = '{ "version": "1.0.0" }' @stdout = StringIO.new @stderr = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end describe 'run' do it 'should print an error and exit if a cookbook name was not provided' do @knife.name_args = [] - @knife.ui.should_receive(:error).with(/you must specify the cookbook.+use the --all/i) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:error).with(/you must specify the cookbook.+use the --all/i) + expect { @knife.run }.to raise_error(SystemExit) end it 'should print an error and exit if an empty cookbook name was provided' do @knife.name_args = [''] - @knife.ui.should_receive(:error).with(/you must specify the cookbook.+use the --all/i) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:error).with(/you must specify the cookbook.+use the --all/i) + expect { @knife.run }.to raise_error(SystemExit) end it 'should generate the metadata for the cookbook' do - @knife.should_receive(:generate_metadata).with('foobar') + expect(@knife).to receive(:generate_metadata).with('foobar') @knife.run end @@ -59,21 +59,21 @@ describe Chef::Knife::CookbookMetadata do "foo" => @foo, "bar" => @bar } - @cookbook_loader.should_receive(:load_cookbooks).and_return(@cookbook_loader) - @knife.should_receive(:generate_metadata).with('foo') - @knife.should_receive(:generate_metadata).with('bar') + expect(@cookbook_loader).to receive(:load_cookbooks).and_return(@cookbook_loader) + expect(@knife).to receive(:generate_metadata).with('foo') + expect(@knife).to receive(:generate_metadata).with('bar') end it 'should generate the metadata for each cookbook' do Chef::Config[:cookbook_path] = @cookbook_dir - Chef::CookbookLoader.should_receive(:new).with(@cookbook_dir).and_return(@cookbook_loader) + expect(Chef::CookbookLoader).to receive(:new).with(@cookbook_dir).and_return(@cookbook_loader) @knife.run end describe 'and with -o or --cookbook-path' do it 'should look in the provided path and generate cookbook metadata' do @knife.config[:cookbook_path] = '/opt/chef/cookbooks' - Chef::CookbookLoader.should_receive(:new).with('/opt/chef/cookbooks').and_return(@cookbook_loader) + expect(Chef::CookbookLoader).to receive(:new).with('/opt/chef/cookbooks').and_return(@cookbook_loader) @knife.run end end @@ -84,21 +84,21 @@ describe Chef::Knife::CookbookMetadata do describe 'generate_metadata' do before(:each) do @knife.config[:cookbook_path] = @cookbook_dir - File.stub(:expand_path).with("#{@cookbook_dir}/foobar/metadata.rb"). + allow(File).to receive(:expand_path).with("#{@cookbook_dir}/foobar/metadata.rb"). and_return("#{@cookbook_dir}/foobar/metadata.rb") end it 'should generate the metadata from metadata.rb if it exists' do - File.should_receive(:exists?).with("#{@cookbook_dir}/foobar/metadata.rb"). + expect(File).to receive(:exists?).with("#{@cookbook_dir}/foobar/metadata.rb"). and_return(true) - @knife.should_receive(:generate_metadata_from_file).with('foobar', "#{@cookbook_dir}/foobar/metadata.rb") + expect(@knife).to receive(:generate_metadata_from_file).with('foobar', "#{@cookbook_dir}/foobar/metadata.rb") @knife.run end it 'should validate the metadata json if metadata.rb does not exist' do - File.should_receive(:exists?).with("#{@cookbook_dir}/foobar/metadata.rb"). + expect(File).to receive(:exists?).with("#{@cookbook_dir}/foobar/metadata.rb"). and_return(false) - @knife.should_receive(:validate_metadata_json).with(@cookbook_dir, 'foobar') + expect(@knife).to receive(:validate_metadata_json).with(@cookbook_dir, 'foobar') @knife.run end end @@ -110,16 +110,16 @@ describe Chef::Knife::CookbookMetadata do end it 'should generate the metatdata json from metatdata.rb' do - Chef::Cookbook::Metadata.stub(:new).and_return(@metadata_mock) - @metadata_mock.should_receive(:name).with('foobar') - @metadata_mock.should_receive(:from_file).with("#{@cookbook_dir}/foobar/metadata.rb") - File.should_receive(:open).with("#{@cookbook_dir}/foobar/metadata.json", 'w'). + allow(Chef::Cookbook::Metadata).to receive(:new).and_return(@metadata_mock) + expect(@metadata_mock).to receive(:name).with('foobar') + expect(@metadata_mock).to receive(:from_file).with("#{@cookbook_dir}/foobar/metadata.rb") + expect(File).to receive(:open).with("#{@cookbook_dir}/foobar/metadata.json", 'w'). and_yield(@json_file_mock) - @json_file_mock.should_receive(:write).with(@json_data) - Chef::JSONCompat.should_receive(:to_json_pretty).with(@metadata_mock). + expect(@json_file_mock).to receive(:write).with(@json_data) + expect(Chef::JSONCompat).to receive(:to_json_pretty).with(@metadata_mock). and_return(@json_data) @knife.generate_metadata_from_file('foobar', "#{@cookbook_dir}/foobar/metadata.rb") - @stderr.string.should match /generating metadata for foobar from #{@cookbook_dir}\/foobar\/metadata\.rb/im + expect(@stderr.string).to match /generating metadata for foobar from #{@cookbook_dir}\/foobar\/metadata\.rb/im end { Chef::Exceptions::ObsoleteDependencySyntax => 'obsolote dependency', @@ -127,32 +127,32 @@ describe Chef::Knife::CookbookMetadata do }.each_pair do |klass, description| it "should print an error and exit when an #{description} syntax exception is encountered" do exception = klass.new("#{description} blah") - Chef::Cookbook::Metadata.stub(:new).and_raise(exception) - lambda { + allow(Chef::Cookbook::Metadata).to receive(:new).and_raise(exception) + expect { @knife.generate_metadata_from_file('foobar', "#{@cookbook_dir}/foobar/metadata.rb") - }.should raise_error(SystemExit) - @stderr.string.should match /error: the cookbook 'foobar' contains invalid or obsolete metadata syntax/im - @stderr.string.should match /in #{@cookbook_dir}\/foobar\/metadata\.rb/im - @stderr.string.should match /#{description} blah/im + }.to raise_error(SystemExit) + expect(@stderr.string).to match /error: the cookbook 'foobar' contains invalid or obsolete metadata syntax/im + expect(@stderr.string).to match /in #{@cookbook_dir}\/foobar\/metadata\.rb/im + expect(@stderr.string).to match /#{description} blah/im end end end describe 'validate_metadata_json' do it 'should validate the metadata json' do - File.should_receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). + expect(File).to receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). and_return(true) - IO.should_receive(:read).with("#{@cookbook_dir}/foobar/metadata.json"). + expect(IO).to receive(:read).with("#{@cookbook_dir}/foobar/metadata.json"). and_return(@json_data) - Chef::Cookbook::Metadata.should_receive(:validate_json).with(@json_data) + expect(Chef::Cookbook::Metadata).to receive(:validate_json).with(@json_data) @knife.validate_metadata_json(@cookbook_dir, 'foobar') end it 'should not try to validate the metadata json if the file does not exist' do - File.should_receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). + expect(File).to receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). and_return(false) - IO.should_not_receive(:read) - Chef::Cookbook::Metadata.should_not_receive(:validate_json) + expect(IO).not_to receive(:read) + expect(Chef::Cookbook::Metadata).not_to receive(:validate_json) @knife.validate_metadata_json(@cookbook_dir, 'foobar') end @@ -160,18 +160,18 @@ describe Chef::Knife::CookbookMetadata do Chef::Exceptions::InvalidVersionConstraint => 'invalid version constraint' }.each_pair do |klass, description| it "should print an error and exit when an #{description} syntax exception is encountered" do - File.should_receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). + expect(File).to receive(:exist?).with("#{@cookbook_dir}/foobar/metadata.json"). and_return(true) - IO.should_receive(:read).with("#{@cookbook_dir}/foobar/metadata.json"). + expect(IO).to receive(:read).with("#{@cookbook_dir}/foobar/metadata.json"). and_return(@json_data) exception = klass.new("#{description} blah") - Chef::Cookbook::Metadata.stub(:validate_json).and_raise(exception) - lambda { + allow(Chef::Cookbook::Metadata).to receive(:validate_json).and_raise(exception) + expect { @knife.validate_metadata_json(@cookbook_dir, 'foobar') - }.should raise_error(SystemExit) - @stderr.string.should match /error: the cookbook 'foobar' contains invalid or obsolete metadata syntax/im - @stderr.string.should match /in #{@cookbook_dir}\/foobar\/metadata\.json/im - @stderr.string.should match /#{description} blah/im + }.to raise_error(SystemExit) + expect(@stderr.string).to match /error: the cookbook 'foobar' contains invalid or obsolete metadata syntax/im + expect(@stderr.string).to match /in #{@cookbook_dir}\/foobar\/metadata\.json/im + expect(@stderr.string).to match /#{description} blah/im end end end diff --git a/spec/unit/knife/cookbook_show_spec.rb b/spec/unit/knife/cookbook_show_spec.rb index b862c3154c..bf480e3678 100644 --- a/spec/unit/knife/cookbook_show_spec.rb +++ b/spec/unit/knife/cookbook_show_spec.rb @@ -26,18 +26,18 @@ describe Chef::Knife::CookbookShow do @knife.config = { } @knife.name_args = [ "cookbook_name" ] @rest = double(Chef::REST) - @knife.stub(:rest).and_return(@rest) - @knife.stub(:pretty_print).and_return(true) - @knife.stub(:output).and_return(true) + allow(@knife).to receive(:rest).and_return(@rest) + allow(@knife).to receive(:pretty_print).and_return(true) + allow(@knife).to receive(:output).and_return(true) end describe "run" do describe "with 0 arguments: help" do it 'should should print usage and exit when given no arguments' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end @@ -56,15 +56,15 @@ describe Chef::Knife::CookbookShow do end it "should show the raw cookbook data" do - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name").and_return(@response) - @knife.should_receive(:format_cookbook_list_for_display).with(@response) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name").and_return(@response) + expect(@knife).to receive(:format_cookbook_list_for_display).with(@response) @knife.run end it "should respect the user-supplied environment" do @knife.config[:environment] = "foo" - @rest.should_receive(:get_rest).with("environments/foo/cookbooks/cookbook_name").and_return(@response) - @knife.should_receive(:format_cookbook_list_for_display).with(@response) + expect(@rest).to receive(:get_rest).with("environments/foo/cookbooks/cookbook_name").and_return(@response) + expect(@knife).to receive(:format_cookbook_list_for_display).with(@response) @knife.run end end @@ -76,8 +76,8 @@ describe Chef::Knife::CookbookShow do end it "should show the specific part of a cookbook" do - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@response) - @knife.should_receive(:output).with(@response) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@response) + expect(@knife).to receive(:output).with(@response) @knife.run end end @@ -101,8 +101,8 @@ describe Chef::Knife::CookbookShow do end it "should print the json of the part" do - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - @knife.should_receive(:output).with(@cookbook_response.manifest["recipes"]) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@knife).to receive(:output).with(@cookbook_response.manifest["recipes"]) @knife.run end end @@ -125,9 +125,9 @@ describe Chef::Knife::CookbookShow do end it "should print the raw result of the request (likely a file!)" do - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - @rest.should_receive(:get_rest).with("http://example.org/files/default.rb", true).and_return(StringIO.new(@response)) - @knife.should_receive(:pretty_print).with(@response) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get_rest).with("http://example.org/files/default.rb", true).and_return(StringIO.new(@response)) + expect(@knife).to receive(:pretty_print).with(@response) @knife.run end end @@ -177,9 +177,9 @@ describe Chef::Knife::CookbookShow do @knife.config[:platform] = "example_platform" @knife.config[:platform_version] = "1.0" @knife.config[:fqdn] = "examplehost.example.org" - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - @rest.should_receive(:get_rest).with("http://example.org/files/1111", true).and_return(StringIO.new(@response)) - @knife.should_receive(:pretty_print).with(@response) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get_rest).with("http://example.org/files/1111", true).and_return(StringIO.new(@response)) + expect(@knife).to receive(:pretty_print).with(@response) @knife.run end end @@ -189,9 +189,9 @@ describe Chef::Knife::CookbookShow do @knife.config[:platform] = "ubuntu" @knife.config[:platform_version] = "1.0" @knife.config[:fqdn] = "differenthost.example.org" - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - @rest.should_receive(:get_rest).with("http://example.org/files/3333", true).and_return(StringIO.new(@response)) - @knife.should_receive(:pretty_print).with(@response) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get_rest).with("http://example.org/files/3333", true).and_return(StringIO.new(@response)) + expect(@knife).to receive(:pretty_print).with(@response) @knife.run end end @@ -201,18 +201,18 @@ describe Chef::Knife::CookbookShow do @knife.config[:platform] = "ubuntu" @knife.config[:platform_version] = "9.10" @knife.config[:fqdn] = "differenthost.example.org" - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - @rest.should_receive(:get_rest).with("http://example.org/files/2222", true).and_return(StringIO.new(@response)) - @knife.should_receive(:pretty_print).with(@response) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get_rest).with("http://example.org/files/2222", true).and_return(StringIO.new(@response)) + expect(@knife).to receive(:pretty_print).with(@response) @knife.run end end describe "with none of the arguments, it should use the default" do it "should pass them all" do - @rest.should_receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - @rest.should_receive(:get_rest).with("http://example.org/files/4444", true).and_return(StringIO.new(@response)) - @knife.should_receive(:pretty_print).with(@response) + expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get_rest).with("http://example.org/files/4444", true).and_return(StringIO.new(@response)) + expect(@knife).to receive(:pretty_print).with(@response) @knife.run end end diff --git a/spec/unit/knife/cookbook_site_download_spec.rb b/spec/unit/knife/cookbook_site_download_spec.rb index 76ce6508d7..6676fb34a1 100644 --- a/spec/unit/knife/cookbook_site_download_spec.rb +++ b/spec/unit/knife/cookbook_site_download_spec.rb @@ -33,9 +33,9 @@ describe Chef::Knife::CookbookSiteDownload do 'latest_version' => "#{@cookbook_api_url}/apache2/versions/#{@version_us}", 'replacement' => 'other_apache2' } - @knife.ui.stub(:stderr).and_return(@stderr) - @knife.stub(:noauth_rest).and_return(@noauth_rest) - @noauth_rest.should_receive(:get_rest). + allow(@knife.ui).to receive(:stderr).and_return(@stderr) + allow(@knife).to receive(:noauth_rest).and_return(@noauth_rest) + expect(@noauth_rest).to receive(:get_rest). with("#{@cookbook_api_url}/apache2"). and_return(@current_data) end @@ -46,9 +46,9 @@ describe Chef::Knife::CookbookSiteDownload do end it 'should warn with info about the replacement' do - @knife.ui.should_receive(:warn). + expect(@knife.ui).to receive(:warn). with(/.+deprecated.+replaced by other_apache2.+/i) - @knife.ui.should_receive(:warn). + expect(@knife.ui).to receive(:warn). with(/use --force.+download.+/i) @knife.run end @@ -61,15 +61,15 @@ describe Chef::Knife::CookbookSiteDownload do @temp_file = double( :path => "/tmp/apache2_#{@version_us}.tgz" ) @file = File.join(Dir.pwd, "apache2-#{@version}.tar.gz") - @noauth_rest.should_receive(:sign_on_redirect=).with(false) + expect(@noauth_rest).to receive(:sign_on_redirect=).with(false) end context 'downloading the latest version' do before do - @noauth_rest.should_receive(:get_rest). + expect(@noauth_rest).to receive(:get_rest). with(@current_data['latest_version']). and_return(@cookbook_data) - @noauth_rest.should_receive(:get_rest). + expect(@noauth_rest).to receive(:get_rest). with(@cookbook_data['file'], true). and_return(@temp_file) end @@ -81,40 +81,40 @@ describe Chef::Knife::CookbookSiteDownload do end it 'should download the latest version' do - @knife.ui.should_receive(:warn). + expect(@knife.ui).to receive(:warn). with(/.+deprecated.+replaced by other_apache2.+/i) - FileUtils.should_receive(:cp).with(@temp_file.path, @file) + expect(FileUtils).to receive(:cp).with(@temp_file.path, @file) @knife.run - @stderr.string.should match /downloading apache2.+version.+#{Regexp.escape(@version)}/i - @stderr.string.should match /cookbook save.+#{Regexp.escape(@file)}/i + expect(@stderr.string).to match /downloading apache2.+version.+#{Regexp.escape(@version)}/i + expect(@stderr.string).to match /cookbook save.+#{Regexp.escape(@file)}/i end end it 'should download the latest version' do - FileUtils.should_receive(:cp).with(@temp_file.path, @file) + expect(FileUtils).to receive(:cp).with(@temp_file.path, @file) @knife.run - @stderr.string.should match /downloading apache2.+version.+#{Regexp.escape(@version)}/i - @stderr.string.should match /cookbook save.+#{Regexp.escape(@file)}/i + expect(@stderr.string).to match /downloading apache2.+version.+#{Regexp.escape(@version)}/i + expect(@stderr.string).to match /cookbook save.+#{Regexp.escape(@file)}/i end context 'with -f or --file' do before do @file = '/opt/chef/cookbooks/apache2.tar.gz' @knife.config[:file] = @file - FileUtils.should_receive(:cp).with(@temp_file.path, @file) + expect(FileUtils).to receive(:cp).with(@temp_file.path, @file) end it 'should download the cookbook to the desired file' do @knife.run - @stderr.string.should match /downloading apache2.+version.+#{Regexp.escape(@version)}/i - @stderr.string.should match /cookbook save.+#{Regexp.escape(@file)}/i + expect(@stderr.string).to match /downloading apache2.+version.+#{Regexp.escape(@version)}/i + expect(@stderr.string).to match /cookbook save.+#{Regexp.escape(@file)}/i end end it 'should provide an accessor to the version' do - FileUtils.stub(:cp).and_return(true) - @knife.version.should == @version + allow(FileUtils).to receive(:cp).and_return(true) + expect(@knife.version).to eq(@version) @knife.run end end @@ -131,16 +131,16 @@ describe Chef::Knife::CookbookSiteDownload do end it 'should download the desired version' do - @noauth_rest.should_receive(:get_rest). + expect(@noauth_rest).to receive(:get_rest). with("#{@cookbook_api_url}/apache2/versions/#{@version_us}"). and_return(@cookbook_data) - @noauth_rest.should_receive(:get_rest). + expect(@noauth_rest).to receive(:get_rest). with(@cookbook_data['file'], true). and_return(@temp_file) - FileUtils.should_receive(:cp).with(@temp_file.path, @file) + expect(FileUtils).to receive(:cp).with(@temp_file.path, @file) @knife.run - @stderr.string.should match /downloading apache2.+version.+#{Regexp.escape(@version)}/i - @stderr.string.should match /cookbook save.+#{Regexp.escape(@file)}/i + expect(@stderr.string).to match /downloading apache2.+version.+#{Regexp.escape(@version)}/i + expect(@stderr.string).to match /cookbook save.+#{Regexp.escape(@file)}/i end end diff --git a/spec/unit/knife/cookbook_site_install_spec.rb b/spec/unit/knife/cookbook_site_install_spec.rb index ff87a81b49..c4bd8f67d2 100644 --- a/spec/unit/knife/cookbook_site_install_spec.rb +++ b/spec/unit/knife/cookbook_site_install_spec.rb @@ -23,7 +23,7 @@ describe Chef::Knife::CookbookSiteInstall do require 'chef/knife/core/cookbook_scm_repo' @stdout = StringIO.new @knife = Chef::Knife::CookbookSiteInstall.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) @knife.config = {} if Chef::Platform.windows? @install_path = 'C:/tmp/chef' @@ -34,18 +34,18 @@ describe Chef::Knife::CookbookSiteInstall do @stdout = StringIO.new @stderr = StringIO.new - @knife.stub(:stderr).and_return(@stdout) - @knife.stub(:stdout).and_return(@stdout) + allow(@knife).to receive(:stderr).and_return(@stdout) + allow(@knife).to receive(:stdout).and_return(@stdout) #Assume all external commands would have succeed. :( - File.stub(:unlink) - File.stub(:rmtree) - @knife.stub(:shell_out!).and_return(true) + allow(File).to receive(:unlink) + allow(File).to receive(:rmtree) + allow(@knife).to receive(:shell_out!).and_return(true) #CookbookSiteDownload Stup @downloader = {} - @knife.stub(:download_cookbook_to).and_return(@downloader) - @downloader.stub(:version).and_return do + allow(@knife).to receive(:download_cookbook_to).and_return(@downloader) + allow(@downloader).to receive(:version) do if @knife.name_args.size == 2 @knife.name_args[1] else @@ -57,49 +57,49 @@ describe Chef::Knife::CookbookSiteInstall do @repo = double(:sanity_check => true, :reset_to_default_state => true, :prepare_to_import => true, :finalize_updates_to => true, :merge_updates_from => true) - Chef::Knife::CookbookSCMRepo.stub(:new).and_return(@repo) + allow(Chef::Knife::CookbookSCMRepo).to receive(:new).and_return(@repo) end describe "run" do it "should return an error if a cookbook name is not provided" do @knife.name_args = [] - @knife.ui.should_receive(:error).with("Please specify a cookbook to download and install.") - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:error).with("Please specify a cookbook to download and install.") + expect { @knife.run }.to raise_error(SystemExit) end it "should return an error if more than two arguments are given" do @knife.name_args = ["foo", "bar", "baz"] - @knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.") - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:error).with("Installing multiple cookbooks at once is not supported.") + expect { @knife.run }.to raise_error(SystemExit) end it "should return an error if the second argument is not a version" do @knife.name_args = ["getting-started", "1pass"] - @knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.") - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:error).with("Installing multiple cookbooks at once is not supported.") + expect { @knife.run }.to raise_error(SystemExit) end it "should return an error if the second argument is a four-digit version" do @knife.name_args = ["getting-started", "0.0.0.1"] - @knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.") - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:error).with("Installing multiple cookbooks at once is not supported.") + expect { @knife.run }.to raise_error(SystemExit) end it "should return an error if the second argument is a one-digit version" do @knife.name_args = ["getting-started", "1"] - @knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.") - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:error).with("Installing multiple cookbooks at once is not supported.") + expect { @knife.run }.to raise_error(SystemExit) end it "should install the specified version if second argument is a three-digit version" do @knife.name_args = ["getting-started", "0.1.0"] @knife.config[:no_deps] = true upstream_file = File.join(@install_path, "getting-started.tar.gz") - @knife.should_receive(:download_cookbook_to).with(upstream_file) - @knife.should_receive(:extract_cookbook).with(upstream_file, "0.1.0") - @knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) - @repo.should_receive(:merge_updates_from).with("getting-started", "0.1.0") + expect(@knife).to receive(:download_cookbook_to).with(upstream_file) + expect(@knife).to receive(:extract_cookbook).with(upstream_file, "0.1.0") + expect(@knife).to receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) + expect(@repo).to receive(:merge_updates_from).with("getting-started", "0.1.0") @knife.run end @@ -107,10 +107,10 @@ describe Chef::Knife::CookbookSiteInstall do @knife.name_args = ["getting-started", "0.1"] @knife.config[:no_deps] = true upstream_file = File.join(@install_path, "getting-started.tar.gz") - @knife.should_receive(:download_cookbook_to).with(upstream_file) - @knife.should_receive(:extract_cookbook).with(upstream_file, "0.1") - @knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) - @repo.should_receive(:merge_updates_from).with("getting-started", "0.1") + expect(@knife).to receive(:download_cookbook_to).with(upstream_file) + expect(@knife).to receive(:extract_cookbook).with(upstream_file, "0.1") + expect(@knife).to receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) + expect(@repo).to receive(:merge_updates_from).with("getting-started", "0.1") @knife.run end @@ -118,10 +118,10 @@ describe Chef::Knife::CookbookSiteInstall do @knife.name_args = ["getting-started"] @knife.config[:no_deps] = true upstream_file = File.join(@install_path, "getting-started.tar.gz") - @knife.should_receive(:download_cookbook_to).with(upstream_file) - @knife.should_receive(:extract_cookbook).with(upstream_file, "0.3.0") - @knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) - @repo.should_receive(:merge_updates_from).with("getting-started", "0.3.0") + expect(@knife).to receive(:download_cookbook_to).with(upstream_file) + expect(@knife).to receive(:extract_cookbook).with(upstream_file, "0.3.0") + expect(@knife).to receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) + expect(@repo).to receive(:merge_updates_from).with("getting-started", "0.3.0") @knife.run end @@ -130,8 +130,8 @@ describe Chef::Knife::CookbookSiteInstall do @knife.config[:use_current_branch] = true @knife.config[:no_deps] = true upstream_file = File.join(@install_path, "getting-started.tar.gz") - @repo.should_not_receive(:prepare_to_import) - @repo.should_not_receive(:reset_to_default_state) + expect(@repo).not_to receive(:prepare_to_import) + expect(@repo).not_to receive(:reset_to_default_state) @knife.run end @@ -140,11 +140,11 @@ describe Chef::Knife::CookbookSiteInstall do @knife.config[:no_deps] = true @knife.name_args = ["getting-started"] upstream_file = File.join(@install_path, "getting-started.tar.gz") - @knife.should_receive(:download_cookbook_to).with(upstream_file) - @knife.should_receive(:extract_cookbook).with(upstream_file, "0.3.0") - @knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) - @repo.should_receive(:merge_updates_from).with("getting-started", "0.3.0") - lambda { @knife.run }.should_not raise_error + expect(@knife).to receive(:download_cookbook_to).with(upstream_file) + expect(@knife).to receive(:extract_cookbook).with(upstream_file, "0.3.0") + expect(@knife).to receive(:clear_existing_files).with(File.join(@install_path, "getting-started")) + expect(@repo).to receive(:merge_updates_from).with("getting-started", "0.3.0") + expect { @knife.run }.not_to raise_error end end end diff --git a/spec/unit/knife/cookbook_site_share_spec.rb b/spec/unit/knife/cookbook_site_share_spec.rb index b85db98d53..0f97261ad4 100644 --- a/spec/unit/knife/cookbook_site_share_spec.rb +++ b/spec/unit/knife/cookbook_site_share_spec.rb @@ -32,27 +32,27 @@ describe Chef::Knife::CookbookSiteShare do @cookbook = Chef::CookbookVersion.new('cookbook_name') @cookbook_loader = double('Chef::CookbookLoader') - @cookbook_loader.stub(:cookbook_exists?).and_return(true) - @cookbook_loader.stub(:[]).and_return(@cookbook) - Chef::CookbookLoader.stub(:new).and_return(@cookbook_loader) + allow(@cookbook_loader).to receive(:cookbook_exists?).and_return(true) + allow(@cookbook_loader).to receive(:[]).and_return(@cookbook) + allow(Chef::CookbookLoader).to receive(:new).and_return(@cookbook_loader) @noauth_rest = double(Chef::REST) - @knife.stub(:noauth_rest).and_return(@noauth_rest) + allow(@knife).to receive(:noauth_rest).and_return(@noauth_rest) @cookbook_uploader = Chef::CookbookUploader.new('herpderp', :rest => "norest") - Chef::CookbookUploader.stub(:new).and_return(@cookbook_uploader) - @cookbook_uploader.stub(:validate_cookbooks).and_return(true) - Chef::CookbookSiteStreamingUploader.stub(:create_build_dir).and_return(Dir.mktmpdir) + allow(Chef::CookbookUploader).to receive(:new).and_return(@cookbook_uploader) + allow(@cookbook_uploader).to receive(:validate_cookbooks).and_return(true) + allow(Chef::CookbookSiteStreamingUploader).to receive(:create_build_dir).and_return(Dir.mktmpdir) - @knife.stub(:shell_out!).and_return(true) + allow(@knife).to receive(:shell_out!).and_return(true) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe 'run' do before(:each) do - @knife.stub(:do_upload).and_return(true) + allow(@knife).to receive(:do_upload).and_return(true) @category_response = { "name" => "cookbook_name", "category" => "Testing Category" @@ -66,72 +66,72 @@ describe Chef::Knife::CookbookSiteShare do end it 'should set true to config[:dry_run] as default' do - @knife.config[:dry_run].should be_false + expect(@knife.config[:dry_run]).to be_falsey end it 'should should print usage and exit when given no arguments' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end it 'should not fail when given only 1 argument and can determine category' do @knife.name_args = ['cookbook_name'] - @noauth_rest.should_receive(:get_rest).with("http://cookbooks.opscode.com/api/v1/cookbooks/cookbook_name").and_return(@category_response) - @knife.should_receive(:do_upload) + expect(@noauth_rest).to receive(:get_rest).with("http://cookbooks.opscode.com/api/v1/cookbooks/cookbook_name").and_return(@category_response) + expect(@knife).to receive(:do_upload) @knife.run end it 'should print error and exit when given only 1 argument and cannot determine category' do @knife.name_args = ['cookbook_name'] - @noauth_rest.should_receive(:get_rest).with("http://cookbooks.opscode.com/api/v1/cookbooks/cookbook_name").and_return(@bad_category_response) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@noauth_rest).to receive(:get_rest).with("http://cookbooks.opscode.com/api/v1/cookbooks/cookbook_name").and_return(@bad_category_response) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end it 'should print error and exit when given only 1 argument and Chef::REST throws an exception' do @knife.name_args = ['cookbook_name'] - @noauth_rest.should_receive(:get_rest).with("http://cookbooks.opscode.com/api/v1/cookbooks/cookbook_name") { raise Errno::ECONNREFUSED, "Connection refused" } - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@noauth_rest).to receive(:get_rest).with("http://cookbooks.opscode.com/api/v1/cookbooks/cookbook_name") { raise Errno::ECONNREFUSED, "Connection refused" } + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end it 'should check if the cookbook exists' do - @cookbook_loader.should_receive(:cookbook_exists?) + expect(@cookbook_loader).to receive(:cookbook_exists?) @knife.run end it "should exit and log to error if the cookbook doesn't exist" do - @cookbook_loader.stub(:cookbook_exists?).and_return(false) - @knife.ui.should_receive(:error) - lambda { @knife.run }.should raise_error(SystemExit) + allow(@cookbook_loader).to receive(:cookbook_exists?).and_return(false) + expect(@knife.ui).to receive(:error) + expect { @knife.run }.to raise_error(SystemExit) end it 'should make a tarball of the cookbook' do - @knife.should_receive(:shell_out!) do |args| - args.to_s.should match(/tar -czf/) + expect(@knife).to receive(:shell_out!) do |args| + expect(args.to_s).to match(/tar -czf/) end @knife.run end it 'should exit and log to error when the tarball creation fails' do - @knife.stub(:shell_out!).and_raise(Chef::Exceptions::Exec) - @knife.ui.should_receive(:error) - lambda { @knife.run }.should raise_error(SystemExit) + allow(@knife).to receive(:shell_out!).and_raise(Chef::Exceptions::Exec) + expect(@knife.ui).to receive(:error) + expect { @knife.run }.to raise_error(SystemExit) end it 'should upload the cookbook and clean up the tarball' do - @knife.should_receive(:do_upload) - FileUtils.should_receive(:rm_rf) + expect(@knife).to receive(:do_upload) + expect(FileUtils).to receive(:rm_rf) @knife.run end context "when the --dry-run flag is specified" do before do - Chef::CookbookSiteStreamingUploader.stub(:create_build_dir).and_return("/var/tmp/dummy") + allow(Chef::CookbookSiteStreamingUploader).to receive(:create_build_dir).and_return("/var/tmp/dummy") @knife.config = { :dry_run => true } - @knife.stub_chain(:shell_out!, :stdout).and_return('file') + allow(@knife).to receive_message_chain(:shell_out!, :stdout).and_return('file') end it "should list files in the tarball" do @@ -152,46 +152,46 @@ describe Chef::Knife::CookbookSiteShare do before(:each) do @upload_response = double('Net::HTTPResponse') - Chef::CookbookSiteStreamingUploader.stub(:post).and_return(@upload_response) + allow(Chef::CookbookSiteStreamingUploader).to receive(:post).and_return(@upload_response) @stdout = StringIO.new @stderr = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:stderr).and_return(@stderr) - File.stub(:open).and_return(true) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) + allow(File).to receive(:open).and_return(true) end it 'should post the cookbook to "https://supermarket.getchef.com"' do response_text = Chef::JSONCompat.to_json({:uri => 'https://supermarket.getchef.com/cookbooks/cookbook_name'}) - @upload_response.stub(:body).and_return(response_text) - @upload_response.stub(:code).and_return(201) - Chef::CookbookSiteStreamingUploader.should_receive(:post).with(/supermarket\.getchef\.com/, anything(), anything(), anything()) + allow(@upload_response).to receive(:body).and_return(response_text) + allow(@upload_response).to receive(:code).and_return(201) + expect(Chef::CookbookSiteStreamingUploader).to receive(:post).with(/supermarket\.getchef\.com/, anything(), anything(), anything()) @knife.run end it 'should alert the user when a version already exists' do response_text = Chef::JSONCompat.to_json({:error_messages => ['Version already exists']}) - @upload_response.stub(:body).and_return(response_text) - @upload_response.stub(:code).and_return(409) - lambda { @knife.run }.should raise_error(SystemExit) - @stderr.string.should match(/ERROR(.+)cookbook already exists/) + allow(@upload_response).to receive(:body).and_return(response_text) + allow(@upload_response).to receive(:code).and_return(409) + expect { @knife.run }.to raise_error(SystemExit) + expect(@stderr.string).to match(/ERROR(.+)cookbook already exists/) end it 'should pass any errors on to the user' do response_text = Chef::JSONCompat.to_json({:error_messages => ["You're holding it wrong"]}) - @upload_response.stub(:body).and_return(response_text) - @upload_response.stub(:code).and_return(403) - lambda { @knife.run }.should raise_error(SystemExit) - @stderr.string.should match("ERROR(.*)You're holding it wrong") + allow(@upload_response).to receive(:body).and_return(response_text) + allow(@upload_response).to receive(:code).and_return(403) + expect { @knife.run }.to raise_error(SystemExit) + expect(@stderr.string).to match("ERROR(.*)You're holding it wrong") end it 'should print the body if no errors are exposed on failure' do response_text = Chef::JSONCompat.to_json({:system_error => "Your call was dropped", :reason => "There's a map for that"}) - @upload_response.stub(:body).and_return(response_text) - @upload_response.stub(:code).and_return(500) - @knife.ui.should_receive(:error).with(/#{Regexp.escape(response_text)}/)#.ordered - @knife.ui.should_receive(:error).with(/Unknown error/)#.ordered - lambda { @knife.run }.should raise_error(SystemExit) + allow(@upload_response).to receive(:body).and_return(response_text) + allow(@upload_response).to receive(:code).and_return(500) + expect(@knife.ui).to receive(:error).with(/#{Regexp.escape(response_text)}/)#.ordered + expect(@knife.ui).to receive(:error).with(/Unknown error/)#.ordered + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/cookbook_site_unshare_spec.rb b/spec/unit/knife/cookbook_site_unshare_spec.rb index 14cda65b43..ec46a8705c 100644 --- a/spec/unit/knife/cookbook_site_unshare_spec.rb +++ b/spec/unit/knife/cookbook_site_unshare_spec.rb @@ -24,13 +24,13 @@ describe Chef::Knife::CookbookSiteUnshare do before(:each) do @knife = Chef::Knife::CookbookSiteUnshare.new @knife.name_args = ['cookbook_name'] - @knife.stub(:confirm).and_return(true) + allow(@knife).to receive(:confirm).and_return(true) @rest = double('Chef::REST') - @rest.stub(:delete_rest).and_return(true) - @knife.stub(:rest).and_return(@rest) + allow(@rest).to receive(:delete_rest).and_return(true) + allow(@knife).to receive(:rest).and_return(@rest) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe 'run' do @@ -38,37 +38,37 @@ describe Chef::Knife::CookbookSiteUnshare do describe 'with no cookbook argument' do it 'should print the usage and exit' do @knife.name_args = [] - @knife.ui.should_receive(:fatal) - @knife.should_receive(:show_usage) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:fatal) + expect(@knife).to receive(:show_usage) + expect { @knife.run }.to raise_error(SystemExit) end end it 'should confirm you want to unshare the cookbook' do - @knife.should_receive(:confirm) + expect(@knife).to receive(:confirm) @knife.run end it 'should send a delete request to the cookbook site' do - @rest.should_receive(:delete_rest) + expect(@rest).to receive(:delete_rest) @knife.run end it 'should log an error and exit when forbidden' do exception = double('403 "Forbidden"', :code => '403') - @rest.stub(:delete_rest).and_raise(Net::HTTPServerException.new('403 "Forbidden"', exception)) - @knife.ui.should_receive(:error) - lambda { @knife.run }.should raise_error(SystemExit) + allow(@rest).to receive(:delete_rest).and_raise(Net::HTTPServerException.new('403 "Forbidden"', exception)) + expect(@knife.ui).to receive(:error) + expect { @knife.run }.to raise_error(SystemExit) end it 'should re-raise any non-forbidden errors on delete_rest' do exception = double('500 "Application Error"', :code => '500') - @rest.stub(:delete_rest).and_raise(Net::HTTPServerException.new('500 "Application Error"', exception)) - lambda { @knife.run }.should raise_error(Net::HTTPServerException) + allow(@rest).to receive(:delete_rest).and_raise(Net::HTTPServerException.new('500 "Application Error"', exception)) + expect { @knife.run }.to raise_error(Net::HTTPServerException) end it 'should log a success message' do - @knife.ui.should_receive(:info) + expect(@knife.ui).to receive(:info) @knife.run end diff --git a/spec/unit/knife/cookbook_test_spec.rb b/spec/unit/knife/cookbook_test_spec.rb index 0e261c02a4..ce74bcaa5d 100644 --- a/spec/unit/knife/cookbook_test_spec.rb +++ b/spec/unit/knife/cookbook_test_spec.rb @@ -26,55 +26,55 @@ describe Chef::Knife::CookbookTest do Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::CookbookTest.new @knife.config[:cookbook_path] = File.join(CHEF_SPEC_DATA,'cookbooks') - @knife.cookbook_loader.stub(:cookbook_exists?).and_return(true) + allow(@knife.cookbook_loader).to receive(:cookbook_exists?).and_return(true) @cookbooks = [] %w{tats central_market jimmy_johns pho}.each do |cookbook_name| @cookbooks << Chef::CookbookVersion.new(cookbook_name) end @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe "run" do it "should test the cookbook" do - @knife.stub(:test_cookbook).and_return(true) + allow(@knife).to receive(:test_cookbook).and_return(true) @knife.name_args = ["italian"] - @knife.should_receive(:test_cookbook).with("italian") + expect(@knife).to receive(:test_cookbook).with("italian") @knife.run end it "should test multiple cookbooks when provided" do - @knife.stub(:test_cookbook).and_return(true) + allow(@knife).to receive(:test_cookbook).and_return(true) @knife.name_args = ["tats", "jimmy_johns"] - @knife.should_receive(:test_cookbook).with("tats") - @knife.should_receive(:test_cookbook).with("jimmy_johns") - @knife.should_not_receive(:test_cookbook).with("central_market") - @knife.should_not_receive(:test_cookbook).with("pho") + expect(@knife).to receive(:test_cookbook).with("tats") + expect(@knife).to receive(:test_cookbook).with("jimmy_johns") + expect(@knife).not_to receive(:test_cookbook).with("central_market") + expect(@knife).not_to receive(:test_cookbook).with("pho") @knife.run end it "should test both ruby and templates" do @knife.name_args = ["example"] - @knife.config[:cookbook_path].should_not be_empty + expect(@knife.config[:cookbook_path]).not_to be_empty Array(@knife.config[:cookbook_path]).reverse.each do |path| - @knife.should_receive(:test_ruby).with(an_instance_of(Chef::Cookbook::SyntaxCheck)) - @knife.should_receive(:test_templates).with(an_instance_of(Chef::Cookbook::SyntaxCheck)) + expect(@knife).to receive(:test_ruby).with(an_instance_of(Chef::Cookbook::SyntaxCheck)) + expect(@knife).to receive(:test_templates).with(an_instance_of(Chef::Cookbook::SyntaxCheck)) end @knife.run end describe "with -a or --all" do it "should test all of the cookbooks" do - @knife.stub(:test_cookbook).and_return(true) + allow(@knife).to receive(:test_cookbook).and_return(true) @knife.config[:all] = true @loader = {} - @loader.stub(:load_cookbooks).and_return(@loader) + allow(@loader).to receive(:load_cookbooks).and_return(@loader) @cookbooks.each do |cookbook| @loader[cookbook.name] = cookbook end - @knife.stub(:cookbook_loader).and_return(@loader) + allow(@knife).to receive(:cookbook_loader).and_return(@loader) @loader.each do |key, cookbook| - @knife.should_receive(:test_cookbook).with(cookbook.name) + expect(@knife).to receive(:test_cookbook).with(cookbook.name) end @knife.run end diff --git a/spec/unit/knife/cookbook_upload_spec.rb b/spec/unit/knife/cookbook_upload_spec.rb index e5c9a40cf1..5dbd456ad8 100644 --- a/spec/unit/knife/cookbook_upload_spec.rb +++ b/spec/unit/knife/cookbook_upload_spec.rb @@ -31,8 +31,8 @@ describe Chef::Knife::CookbookUpload do let(:cookbook_loader) do cookbook_loader = cookbooks_by_name.dup - cookbook_loader.stub(:merged_cookbooks).and_return([]) - cookbook_loader.stub(:load_cookbooks).and_return(cookbook_loader) + allow(cookbook_loader).to receive(:merged_cookbooks).and_return([]) + allow(cookbook_loader).to receive(:load_cookbooks).and_return(cookbook_loader) cookbook_loader end @@ -45,23 +45,23 @@ describe Chef::Knife::CookbookUpload do let(:knife) do k = Chef::Knife::CookbookUpload.new k.name_args = name_args - k.ui.stub(:stdout).and_return(output) - k.ui.stub(:stderr).and_return(output) + allow(k.ui).to receive(:stdout).and_return(output) + allow(k.ui).to receive(:stderr).and_return(output) k end before(:each) do - Chef::CookbookLoader.stub(:new).and_return(cookbook_loader) + allow(Chef::CookbookLoader).to receive(:new).and_return(cookbook_loader) end describe 'with --concurrency' do it 'should upload cookbooks with predefined concurrency' do - Chef::CookbookVersion.stub(:list_all_versions).and_return({}) + allow(Chef::CookbookVersion).to receive(:list_all_versions).and_return({}) knife.config[:concurrency] = 3 test_cookbook = Chef::CookbookVersion.new('test_cookbook', '/tmp/blah') - cookbook_loader.stub(:each).and_yield("test_cookbook", test_cookbook) - cookbook_loader.stub(:cookbook_names).and_return(["test_cookbook"]) - Chef::CookbookUploader.should_receive(:new). + allow(cookbook_loader).to receive(:each).and_yield("test_cookbook", test_cookbook) + allow(cookbook_loader).to receive(:cookbook_names).and_return(["test_cookbook"]) + expect(Chef::CookbookUploader).to receive(:new). with( kind_of(Array), { :force => nil, :concurrency => 3}). and_return(double("Chef::CookbookUploader", :upload_cookbooks=> true)) knife.run @@ -70,26 +70,26 @@ describe Chef::Knife::CookbookUpload do describe 'run' do before(:each) do - Chef::CookbookUploader.stub(:new => cookbook_uploader) - Chef::CookbookVersion.stub(:list_all_versions).and_return({}) + allow(Chef::CookbookUploader).to receive_messages(:new => cookbook_uploader) + allow(Chef::CookbookVersion).to receive(:list_all_versions).and_return({}) end it 'should print usage and exit when a cookbook name is not provided' do knife.name_args = [] - knife.should_receive(:show_usage) - knife.ui.should_receive(:fatal) - lambda { knife.run }.should raise_error(SystemExit) + expect(knife).to receive(:show_usage) + expect(knife.ui).to receive(:fatal) + expect { knife.run }.to raise_error(SystemExit) end describe 'when specifying a cookbook name' do it 'should upload the cookbook' do - knife.should_receive(:upload).once + expect(knife).to receive(:upload).once knife.run end it 'should report on success' do - knife.should_receive(:upload).once - knife.ui.should_receive(:info).with(/Uploaded 1 cookbook/) + expect(knife).to receive(:upload).once + expect(knife.ui).to receive(:info).with(/Uploaded 1 cookbook/) knife.run end end @@ -97,7 +97,7 @@ describe Chef::Knife::CookbookUpload do describe 'when specifying the same cookbook name twice' do it 'should upload the cookbook only once' do knife.name_args = ['test_cookbook', 'test_cookbook'] - knife.should_receive(:upload).once + expect(knife).to receive(:upload).once knife.run end end @@ -105,8 +105,8 @@ describe Chef::Knife::CookbookUpload do context "when uploading a cookbook that uses deprecated overlays" do before do - cookbook_loader.stub(:merged_cookbooks).and_return(['test_cookbook']) - cookbook_loader.stub(:merged_cookbook_paths). + allow(cookbook_loader).to receive(:merged_cookbooks).and_return(['test_cookbook']) + allow(cookbook_loader).to receive(:merged_cookbook_paths). and_return({'test_cookbook' => %w{/path/one/test_cookbook /path/two/test_cookbook}}) end @@ -123,7 +123,7 @@ test_cookbook: /path/one/test_cookbook /path/two/test_cookbook E - output.string.should include(expected_message) + expect(output.string).to include(expected_message) end end @@ -139,17 +139,17 @@ E end it "should read only one cookbook" do - cookbook_loader.should_receive(:[]).once.with('test_cookbook1').and_call_original + expect(cookbook_loader).to receive(:[]).once.with('test_cookbook1').and_call_original knife.run end it "should not read all cookbooks" do - cookbook_loader.should_not_receive(:load_cookbooks) + expect(cookbook_loader).not_to receive(:load_cookbooks) knife.run end it "should upload only one cookbook" do - knife.should_receive(:upload).exactly(1).times + expect(knife).to receive(:upload).exactly(1).times knife.run end end @@ -181,13 +181,13 @@ E it "should upload all dependencies once" do knife.config[:depends] = true - knife.stub(:cookbook_names).and_return(["test_cookbook1", "test_cookbook2", "test_cookbook3"]) - knife.should_receive(:upload).exactly(3).times - lambda do + allow(knife).to receive(:cookbook_names).and_return(["test_cookbook1", "test_cookbook2", "test_cookbook3"]) + expect(knife).to receive(:upload).exactly(3).times + expect do Timeout::timeout(5) do knife.run end - end.should_not raise_error + end.not_to raise_error end end @@ -196,50 +196,50 @@ E before(:each) do cookbook.metadata.depends("dependency") - cookbook_loader.stub(:[]) do |ckbk| + allow(cookbook_loader).to receive(:[]) do |ckbk| { "test_cookbook" => cookbook, "dependency" => cookbook_dependency}[ckbk] end - knife.stub(:cookbook_names).and_return(["cookbook_dependency", "test_cookbook"]) + allow(knife).to receive(:cookbook_names).and_return(["cookbook_dependency", "test_cookbook"]) @stdout, @stderr, @stdin = StringIO.new, StringIO.new, StringIO.new knife.ui = Chef::Knife::UI.new(@stdout, @stderr, @stdin, {}) end it 'should exit and not upload the cookbook' do - cookbook_loader.should_receive(:[]).once.with('test_cookbook') - cookbook_loader.should_not_receive(:load_cookbooks) - cookbook_uploader.should_not_receive(:upload_cookbooks) + expect(cookbook_loader).to receive(:[]).once.with('test_cookbook') + expect(cookbook_loader).not_to receive(:load_cookbooks) + expect(cookbook_uploader).not_to receive(:upload_cookbooks) expect {knife.run}.to raise_error(SystemExit) end it 'should output a message for a single missing dependency' do expect {knife.run}.to raise_error(SystemExit) - @stderr.string.should include('Cookbook test_cookbook depends on cookbooks which are not currently') - @stderr.string.should include('being uploaded and cannot be found on the server.') - @stderr.string.should include("The missing cookbook(s) are: 'dependency' version '>= 0.0.0'") + expect(@stderr.string).to include('Cookbook test_cookbook depends on cookbooks which are not currently') + expect(@stderr.string).to include('being uploaded and cannot be found on the server.') + expect(@stderr.string).to include("The missing cookbook(s) are: 'dependency' version '>= 0.0.0'") end it 'should output a message for a multiple missing dependencies which are concatenated' do cookbook_dependency2 = Chef::CookbookVersion.new('dependency2') cookbook.metadata.depends("dependency2") - cookbook_loader.stub(:[]) do |ckbk| + allow(cookbook_loader).to receive(:[]) do |ckbk| { "test_cookbook" => cookbook, "dependency" => cookbook_dependency, "dependency2" => cookbook_dependency2}[ckbk] end - knife.stub(:cookbook_names).and_return(["dependency", "dependency2", "test_cookbook"]) + allow(knife).to receive(:cookbook_names).and_return(["dependency", "dependency2", "test_cookbook"]) expect {knife.run}.to raise_error(SystemExit) - @stderr.string.should include('Cookbook test_cookbook depends on cookbooks which are not currently') - @stderr.string.should include('being uploaded and cannot be found on the server.') - @stderr.string.should include("The missing cookbook(s) are:") - @stderr.string.should include("'dependency' version '>= 0.0.0'") - @stderr.string.should include("'dependency2' version '>= 0.0.0'") + expect(@stderr.string).to include('Cookbook test_cookbook depends on cookbooks which are not currently') + expect(@stderr.string).to include('being uploaded and cannot be found on the server.') + expect(@stderr.string).to include("The missing cookbook(s) are:") + expect(@stderr.string).to include("'dependency' version '>= 0.0.0'") + expect(@stderr.string).to include("'dependency2' version '>= 0.0.0'") end end it "should freeze the version of the cookbooks if --freeze is specified" do knife.config[:freeze] = true - cookbook.should_receive(:freeze_version).once + expect(cookbook).to receive(:freeze_version).once knife.run end @@ -248,25 +248,25 @@ E knife.config[:all] = true @test_cookbook1 = Chef::CookbookVersion.new('test_cookbook1', '/tmp/blah') @test_cookbook2 = Chef::CookbookVersion.new('test_cookbook2', '/tmp/blah') - cookbook_loader.stub(:each).and_yield("test_cookbook1", @test_cookbook1).and_yield("test_cookbook2", @test_cookbook2) - cookbook_loader.stub(:cookbook_names).and_return(["test_cookbook1", "test_cookbook2"]) + allow(cookbook_loader).to receive(:each).and_yield("test_cookbook1", @test_cookbook1).and_yield("test_cookbook2", @test_cookbook2) + allow(cookbook_loader).to receive(:cookbook_names).and_return(["test_cookbook1", "test_cookbook2"]) end it 'should upload all cookbooks' do - knife.should_receive(:upload).once + expect(knife).to receive(:upload).once knife.run end it 'should report on success' do - knife.should_receive(:upload).once - knife.ui.should_receive(:info).with(/Uploaded all cookbooks/) + expect(knife).to receive(:upload).once + expect(knife.ui).to receive(:info).with(/Uploaded all cookbooks/) knife.run end it 'should update the version constraints for an environment' do - knife.stub(:assert_environment_valid!).and_return(true) + allow(knife).to receive(:assert_environment_valid!).and_return(true) knife.config[:environment] = "production" - knife.should_receive(:update_version_constraints).once + expect(knife).to receive(:update_version_constraints).once knife.run end end @@ -274,21 +274,21 @@ E describe 'when a frozen cookbook exists on the server' do it 'should fail to replace it' do exception = Chef::Exceptions::CookbookFrozen.new - cookbook_uploader.should_receive(:upload_cookbooks). + expect(cookbook_uploader).to receive(:upload_cookbooks). and_raise(exception) - knife.ui.stub(:error) - knife.ui.should_receive(:error).with(exception) - lambda { knife.run }.should raise_error(SystemExit) + allow(knife.ui).to receive(:error) + expect(knife.ui).to receive(:error).with(exception) + expect { knife.run }.to raise_error(SystemExit) end it 'should not update the version constraints for an environment' do - knife.stub(:assert_environment_valid!).and_return(true) + allow(knife).to receive(:assert_environment_valid!).and_return(true) knife.config[:environment] = "production" - knife.stub(:upload).and_raise(Chef::Exceptions::CookbookFrozen) - knife.ui.should_receive(:error).with(/Failed to upload 1 cookbook/) - knife.ui.should_receive(:warn).with(/Not updating version constraints/) - knife.should_not_receive(:update_version_constraints) - lambda { knife.run }.should raise_error(SystemExit) + allow(knife).to receive(:upload).and_raise(Chef::Exceptions::CookbookFrozen) + expect(knife.ui).to receive(:error).with(/Failed to upload 1 cookbook/) + expect(knife.ui).to receive(:warn).with(/Not updating version constraints/) + expect(knife).not_to receive(:update_version_constraints) + expect { knife.run }.to raise_error(SystemExit) end end end # run diff --git a/spec/unit/knife/core/bootstrap_context_spec.rb b/spec/unit/knife/core/bootstrap_context_spec.rb index cd53088419..1291571358 100644 --- a/spec/unit/knife/core/bootstrap_context_spec.rb +++ b/spec/unit/knife/core/bootstrap_context_spec.rb @@ -35,18 +35,18 @@ describe Chef::Knife::Core::BootstrapContext do subject(:bootstrap_context) { described_class.new(config, run_list, chef_config, secret) } it "runs chef with the first-boot.json in the _default environment" do - bootstrap_context.start_chef.should eq "chef-client -j /etc/chef/first-boot.json -E _default" + expect(bootstrap_context.start_chef).to eq "chef-client -j /etc/chef/first-boot.json -E _default" end describe "when in verbosity mode" do let(:config) { {:verbosity => 2} } it "adds '-l debug' when verbosity is >= 2" do - bootstrap_context.start_chef.should eq "chef-client -j /etc/chef/first-boot.json -l debug -E _default" + expect(bootstrap_context.start_chef).to eq "chef-client -j /etc/chef/first-boot.json -l debug -E _default" end end it "reads the validation key" do - bootstrap_context.validation_key.should eq IO.read(File.join(CHEF_SPEC_DATA, 'ssl', 'private_key.pem')) + expect(bootstrap_context.validation_key).to eq IO.read(File.join(CHEF_SPEC_DATA, 'ssl', 'private_key.pem')) end it "generates the config file data" do @@ -56,7 +56,7 @@ chef_server_url "http://chef.example.com:4444" validation_client_name "chef-validator-testing" # Using default node name (fqdn) EXPECTED - bootstrap_context.config_content.should eq expected + expect(bootstrap_context.config_content).to eq expected end it "does not set a default log_level" do @@ -66,14 +66,14 @@ EXPECTED describe "alternate chef-client path" do let(:chef_config){ {:chef_client_path => '/usr/local/bin/chef-client'} } it "runs chef-client from another path when specified" do - bootstrap_context.start_chef.should eq "/usr/local/bin/chef-client -j /etc/chef/first-boot.json -E _default" + expect(bootstrap_context.start_chef).to eq "/usr/local/bin/chef-client -j /etc/chef/first-boot.json -E _default" end end describe "validation key path that contains a ~" do let(:chef_config){ {:validation_key => '~/my.key'} } it "reads the validation key when it contains a ~" do - IO.should_receive(:read).with(File.expand_path("my.key", ENV['HOME'])) + expect(IO).to receive(:read).with(File.expand_path("my.key", ENV['HOME'])) bootstrap_context.validation_key end end @@ -81,44 +81,44 @@ EXPECTED describe "when an explicit node name is given" do let(:config){ {:chef_node_name => 'foobar.example.com' }} it "sets the node name in the client.rb" do - bootstrap_context.config_content.should match(/node_name "foobar\.example\.com"/) + expect(bootstrap_context.config_content).to match(/node_name "foobar\.example\.com"/) end end describe "when bootstrapping into a specific environment" do let(:chef_config){ {:environment => "prodtastic"} } it "starts chef in the configured environment" do - bootstrap_context.start_chef.should == 'chef-client -j /etc/chef/first-boot.json -E prodtastic' + expect(bootstrap_context.start_chef).to eq('chef-client -j /etc/chef/first-boot.json -E prodtastic') end end describe "when JSON attributes are given" do let(:config) { {:first_boot_attributes => {:baz => :quux}} } it "adds the attributes to first_boot" do - Chef::JSONCompat.to_json(bootstrap_context.first_boot).should eq(Chef::JSONCompat.to_json({:baz => :quux, :run_list => run_list})) + expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({:baz => :quux, :run_list => run_list})) end end describe "when JSON attributes are NOT given" do it "sets first_boot equal to run_list" do - Chef::JSONCompat.to_json(bootstrap_context.first_boot).should eq(Chef::JSONCompat.to_json({:run_list => run_list})) + expect(Chef::JSONCompat.to_json(bootstrap_context.first_boot)).to eq(Chef::JSONCompat.to_json({:run_list => run_list})) end end describe "when an encrypted_data_bag_secret is provided" do let(:secret) { "supersekret" } it "reads the encrypted_data_bag_secret" do - bootstrap_context.encrypted_data_bag_secret.should eq "supersekret" + expect(bootstrap_context.encrypted_data_bag_secret).to eq "supersekret" end end describe "to support compatibility with existing templates" do it "sets the @config instance variable" do - bootstrap_context.instance_variable_get(:@config).should eq config + expect(bootstrap_context.instance_variable_get(:@config)).to eq config end it "sets the @run_list instance variable" do - bootstrap_context.instance_variable_get(:@run_list).should eq run_list + expect(bootstrap_context.instance_variable_get(:@run_list)).to eq run_list end end @@ -130,7 +130,7 @@ EXPECTED end it "should send the full version to the installer" do - bootstrap_context.latest_current_chef_version_string.should eq("-v 11.12.4") + expect(bootstrap_context.latest_current_chef_version_string).to eq("-v 11.12.4") end end @@ -142,20 +142,20 @@ EXPECTED end it "should send the full version to the installer and set the pre-release flag" do - bootstrap_context.latest_current_chef_version_string.should eq("-v 11.12.4.rc.0 -p") + expect(bootstrap_context.latest_current_chef_version_string).to eq("-v 11.12.4.rc.0 -p") end end describe "when a bootstrap_version is not specified" do it "should send the latest current to the installer" do # Intentionally hard coded in order not to replicate the logic. - bootstrap_context.latest_current_chef_version_string.should eq("-v #{Chef::VERSION.to_i}") + expect(bootstrap_context.latest_current_chef_version_string).to eq("-v #{Chef::VERSION.to_i}") end end describe "ssl_verify_mode" do it "isn't set in the config_content by default" do - bootstrap_context.config_content.should_not include("ssl_verify_mode") + expect(bootstrap_context.config_content).not_to include("ssl_verify_mode") end describe "when configured in config" do @@ -166,14 +166,14 @@ EXPECTED end it "uses the config value" do - bootstrap_context.config_content.should include("ssl_verify_mode :verify_peer") + expect(bootstrap_context.config_content).to include("ssl_verify_mode :verify_peer") end describe "when configured via CLI" do let(:config) {{:node_ssl_verify_mode => "none"}} it "uses CLI value" do - bootstrap_context.config_content.should include("ssl_verify_mode :verify_none") + expect(bootstrap_context.config_content).to include("ssl_verify_mode :verify_none") end end end @@ -181,7 +181,7 @@ EXPECTED describe "verify_api_cert" do it "isn't set in the config_content by default" do - bootstrap_context.config_content.should_not include("verify_api_cert") + expect(bootstrap_context.config_content).not_to include("verify_api_cert") end describe "when configured in config" do @@ -192,14 +192,14 @@ EXPECTED end it "uses the config value" do - bootstrap_context.config_content.should include("verify_api_cert false") + expect(bootstrap_context.config_content).to include("verify_api_cert false") end describe "when configured via CLI" do let(:config) {{:node_verify_api_cert => true}} it "uses CLI value" do - bootstrap_context.config_content.should include("verify_api_cert true") + expect(bootstrap_context.config_content).to include("verify_api_cert true") end end end diff --git a/spec/unit/knife/core/cookbook_scm_repo_spec.rb b/spec/unit/knife/core/cookbook_scm_repo_spec.rb index 69da5400b0..2d66df31c1 100644 --- a/spec/unit/knife/core/cookbook_scm_repo_spec.rb +++ b/spec/unit/knife/core/cookbook_scm_repo_spec.rb @@ -39,45 +39,45 @@ BRANCHES end it "has a path to the cookbook repo" do - @cookbook_repo.repo_path.should == @repo_path + expect(@cookbook_repo.repo_path).to eq(@repo_path) end it "has a default branch" do - @cookbook_repo.default_branch.should == 'master' + expect(@cookbook_repo.default_branch).to eq('master') end describe "when sanity checking the repo" do it "exits when the directory does not exist" do - ::File.should_receive(:directory?).with(@repo_path).and_return(false) - lambda {@cookbook_repo.sanity_check}.should raise_error(SystemExit) + expect(::File).to receive(:directory?).with(@repo_path).and_return(false) + expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) end describe "and the repo dir exists" do before do - ::File.stub(:directory?).with(@repo_path).and_return(true) + allow(::File).to receive(:directory?).with(@repo_path).and_return(true) end it "exits when there is no git repo" do - ::File.stub(:directory?).with(/.*\.git/).and_return(false) - lambda {@cookbook_repo.sanity_check}.should raise_error(SystemExit) + allow(::File).to receive(:directory?).with(/.*\.git/).and_return(false) + expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) end describe "and the repo is a git repo" do before do - ::File.stub(:directory?).with(File.join(@repo_path, '.git')).and_return(true) + allow(::File).to receive(:directory?).with(File.join(@repo_path, '.git')).and_return(true) end it "exits when the default branch doesn't exist" do @nobranches = Mixlib::ShellOut.new.tap {|s|s.stdout.replace "\n"} - @cookbook_repo.should_receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@nobranches) - lambda {@cookbook_repo.sanity_check}.should raise_error(SystemExit) + expect(@cookbook_repo).to receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@nobranches) + expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) end describe "and the default branch exists" do before do @master_branch = Mixlib::ShellOut.new @master_branch.stdout.replace "* master\n" - @cookbook_repo.should_receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@master_branch) + expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@master_branch) end it "exits when the git repo is dirty" do @@ -85,14 +85,14 @@ BRANCHES @dirty_status.stdout.replace(<<-DIRTY) M chef/lib/chef/knife/cookbook_site_vendor.rb DIRTY - @cookbook_repo.should_receive(:shell_out!).with('git status --porcelain', :cwd => @repo_path).and_return(@dirty_status) - lambda {@cookbook_repo.sanity_check}.should raise_error(SystemExit) + expect(@cookbook_repo).to receive(:shell_out!).with('git status --porcelain', :cwd => @repo_path).and_return(@dirty_status) + expect {@cookbook_repo.sanity_check}.to raise_error(SystemExit) end describe "and the repo is clean" do before do @clean_status = Mixlib::ShellOut.new.tap {|s| s.stdout.replace("\n")} - @cookbook_repo.stub(:shell_out!).with('git status --porcelain', :cwd => @repo_path).and_return(@clean_status) + allow(@cookbook_repo).to receive(:shell_out!).with('git status --porcelain', :cwd => @repo_path).and_return(@clean_status) end it "passes the sanity check" do @@ -106,35 +106,35 @@ DIRTY end it "resets to default state by checking out the default branch" do - @cookbook_repo.should_receive(:shell_out!).with('git checkout master', :cwd => @repo_path) + expect(@cookbook_repo).to receive(:shell_out!).with('git checkout master', :cwd => @repo_path) @cookbook_repo.reset_to_default_state end it "determines if a the pristine copy branch exists" do - @cookbook_repo.should_receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) - @cookbook_repo.branch_exists?("chef-vendor-apache2").should be_true - @cookbook_repo.should_receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) - @cookbook_repo.branch_exists?("chef-vendor-nginx").should be_false + expect(@cookbook_repo).to receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) + expect(@cookbook_repo.branch_exists?("chef-vendor-apache2")).to be_truthy + expect(@cookbook_repo).to receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) + expect(@cookbook_repo.branch_exists?("chef-vendor-nginx")).to be_falsey end it "determines if a the branch not exists correctly without substring search" do - @cookbook_repo.should_receive(:shell_out!).twice.with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) - @cookbook_repo.should_not be_branch_exists("chef-vendor-absent") - @cookbook_repo.should be_branch_exists("chef-vendor-absent-new") + expect(@cookbook_repo).to receive(:shell_out!).twice.with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) + expect(@cookbook_repo).not_to be_branch_exists("chef-vendor-absent") + expect(@cookbook_repo).to be_branch_exists("chef-vendor-absent-new") end describe "when the pristine copy branch does not exist" do it "prepares for import by creating the pristine copy branch" do - @cookbook_repo.should_receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) - @cookbook_repo.should_receive(:shell_out!).with('git checkout -b chef-vendor-nginx', :cwd => @repo_path) + expect(@cookbook_repo).to receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) + expect(@cookbook_repo).to receive(:shell_out!).with('git checkout -b chef-vendor-nginx', :cwd => @repo_path) @cookbook_repo.prepare_to_import("nginx") end end describe "when the pristine copy branch does exist" do it "prepares for import by checking out the pristine copy branch" do - @cookbook_repo.should_receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) - @cookbook_repo.should_receive(:shell_out!).with('git checkout chef-vendor-apache2', :cwd => @repo_path) + expect(@cookbook_repo).to receive(:shell_out!).with('git branch --no-color', :cwd => @repo_path).and_return(@branch_list) + expect(@cookbook_repo).to receive(:shell_out!).with('git checkout chef-vendor-apache2', :cwd => @repo_path) @cookbook_repo.prepare_to_import("apache2") end end @@ -143,15 +143,15 @@ DIRTY before do @updates = Mixlib::ShellOut.new @updates.stdout.replace("\n") - @cookbook_repo.stub(:shell_out!).with('git status --porcelain -- apache2', :cwd => @repo_path).and_return(@updates) + allow(@cookbook_repo).to receive(:shell_out!).with('git status --porcelain -- apache2', :cwd => @repo_path).and_return(@updates) end it "shows no changes in the pristine copy" do - @cookbook_repo.updated?('apache2').should be_false + expect(@cookbook_repo.updated?('apache2')).to be_falsey end it "does nothing to finalize the updates" do - @cookbook_repo.finalize_updates_to('apache2', '1.2.3').should be_false + expect(@cookbook_repo.finalize_updates_to('apache2', '1.2.3')).to be_falsey end end @@ -159,18 +159,18 @@ DIRTY before do @updates = Mixlib::ShellOut.new @updates.stdout.replace(" M cookbooks/apache2/recipes/default.rb\n") - @cookbook_repo.stub(:shell_out!).with('git status --porcelain -- apache2', :cwd => @repo_path).and_return(@updates) + allow(@cookbook_repo).to receive(:shell_out!).with('git status --porcelain -- apache2', :cwd => @repo_path).and_return(@updates) end it "shows changes in the pristine copy" do - @cookbook_repo.updated?('apache2').should be_true + expect(@cookbook_repo.updated?('apache2')).to be_truthy end it "commits the changes to the repo and tags the commit" do - @cookbook_repo.should_receive(:shell_out!).with("git add apache2", :cwd => @repo_path) - @cookbook_repo.should_receive(:shell_out!).with("git commit -m \"Import apache2 version 1.2.3\" -- apache2", :cwd => @repo_path) - @cookbook_repo.should_receive(:shell_out!).with("git tag -f cookbook-site-imported-apache2-1.2.3", :cwd => @repo_path) - @cookbook_repo.finalize_updates_to("apache2", "1.2.3").should be_true + expect(@cookbook_repo).to receive(:shell_out!).with("git add apache2", :cwd => @repo_path) + expect(@cookbook_repo).to receive(:shell_out!).with("git commit -m \"Import apache2 version 1.2.3\" -- apache2", :cwd => @repo_path) + expect(@cookbook_repo).to receive(:shell_out!).with("git tag -f cookbook-site-imported-apache2-1.2.3", :cwd => @repo_path) + expect(@cookbook_repo.finalize_updates_to("apache2", "1.2.3")).to be_truthy end end @@ -180,7 +180,7 @@ DIRTY end it "resets to default state by checking out the default branch" do - @cookbook_repo.should_receive(:shell_out!).with('git checkout develop', :cwd => @repo_path) + expect(@cookbook_repo).to receive(:shell_out!).with('git checkout develop', :cwd => @repo_path) @cookbook_repo.reset_to_default_state end end diff --git a/spec/unit/knife/core/object_loader_spec.rb b/spec/unit/knife/core/object_loader_spec.rb index 53a538da91..67fa858029 100644 --- a/spec/unit/knife/core/object_loader_spec.rb +++ b/spec/unit/knife/core/object_loader_spec.rb @@ -24,17 +24,17 @@ describe Chef::Knife::Core::ObjectLoader do before(:each) do @knife = Chef::Knife.new @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) Dir.chdir(File.join(CHEF_SPEC_DATA, 'object_loader')) end shared_examples_for "Chef object" do |chef_class| it "should create a #{chef_class} object" do - @object.should be_a_kind_of(chef_class) + expect(@object).to be_a_kind_of(chef_class) end it "should has a attribute 'name'" do - @object.name.should eql('test') + expect(@object.name).to eql('test') end end diff --git a/spec/unit/knife/core/subcommand_loader_spec.rb b/spec/unit/knife/core/subcommand_loader_spec.rb index 53664cb528..66c202f680 100644 --- a/spec/unit/knife/core/subcommand_loader_spec.rb +++ b/spec/unit/knife/core/subcommand_loader_spec.rb @@ -20,22 +20,22 @@ require 'spec_helper' describe Chef::Knife::SubcommandLoader do before do - Chef::Platform.stub(:windows?) { false } + allow(Chef::Platform).to receive(:windows?) { false } @home = File.join(CHEF_SPEC_DATA, 'knife-home') @env = {'HOME' => @home} @loader = Chef::Knife::SubcommandLoader.new(File.join(CHEF_SPEC_DATA, 'knife-site-subcommands'), @env) end it "builds a list of the core subcommand file require paths" do - @loader.subcommand_files.should_not be_empty + expect(@loader.subcommand_files).not_to be_empty @loader.subcommand_files.each do |require_path| - require_path.should match(/chef\/knife\/.*|plugins\/knife\/.*/) + expect(require_path).to match(/chef\/knife\/.*|plugins\/knife\/.*/) end end it "finds files installed via rubygems" do - @loader.find_subcommands_via_rubygems.should include('chef/knife/node_create') - @loader.find_subcommands_via_rubygems.each {|rel_path, abs_path| abs_path.should match(%r[chef/knife/.+])} + expect(@loader.find_subcommands_via_rubygems).to include('chef/knife/node_create') + @loader.find_subcommands_via_rubygems.each {|rel_path, abs_path| expect(abs_path).to match(%r[chef/knife/.+])} end it "finds files from latest version of installed gems" do @@ -44,33 +44,33 @@ describe Chef::Knife::SubcommandLoader do '/usr/lib/ruby/gems/knife-ec2-0.5.12/lib/chef/knife/ec2_base.rb', '/usr/lib/ruby/gems/knife-ec2-0.5.12/lib/chef/knife/ec2_otherstuff.rb' ] - $LOAD_PATH.should_receive(:map).and_return([]) + expect($LOAD_PATH).to receive(:map).and_return([]) if Gem::Specification.respond_to? :latest_specs - Gem::Specification.should_receive(:latest_specs).with(true).and_return(gems) - gems[0].should_receive(:matches_for_glob).with(/chef\/knife\/\*\.rb\{(.*),\.rb,(.*)\}/).and_return(gem_files) + expect(Gem::Specification).to receive(:latest_specs).with(true).and_return(gems) + expect(gems[0]).to receive(:matches_for_glob).with(/chef\/knife\/\*\.rb\{(.*),\.rb,(.*)\}/).and_return(gem_files) else - Gem.source_index.should_receive(:latest_specs).with(true).and_return(gems) - gems[0].should_receive(:require_paths).twice.and_return(['lib']) - gems[0].should_receive(:full_gem_path).and_return('/usr/lib/ruby/gems/knife-ec2-0.5.12') - Dir.should_receive(:[]).with('/usr/lib/ruby/gems/knife-ec2-0.5.12/lib/chef/knife/*.rb').and_return(gem_files) + expect(Gem.source_index).to receive(:latest_specs).with(true).and_return(gems) + expect(gems[0]).to receive(:require_paths).twice.and_return(['lib']) + expect(gems[0]).to receive(:full_gem_path).and_return('/usr/lib/ruby/gems/knife-ec2-0.5.12') + expect(Dir).to receive(:[]).with('/usr/lib/ruby/gems/knife-ec2-0.5.12/lib/chef/knife/*.rb').and_return(gem_files) end - @loader.should_receive(:find_subcommands_via_dirglob).and_return({}) - @loader.find_subcommands_via_rubygems.values.select { |file| file =~ /knife-ec2/ }.sort.should == gem_files + expect(@loader).to receive(:find_subcommands_via_dirglob).and_return({}) + expect(@loader.find_subcommands_via_rubygems.values.select { |file| file =~ /knife-ec2/ }.sort).to eq(gem_files) end it "finds files using a dirglob when rubygems is not available" do - @loader.find_subcommands_via_dirglob.should include('chef/knife/node_create') - @loader.find_subcommands_via_dirglob.each {|rel_path, abs_path| abs_path.should match(%r[chef/knife/.+])} + expect(@loader.find_subcommands_via_dirglob).to include('chef/knife/node_create') + @loader.find_subcommands_via_dirglob.each {|rel_path, abs_path| expect(abs_path).to match(%r[chef/knife/.+])} end it "finds user-specific subcommands in the user's ~/.chef directory" do expected_command = File.join(@home, '.chef', 'plugins', 'knife', 'example_home_subcommand.rb') - @loader.site_subcommands.should include(expected_command) + expect(@loader.site_subcommands).to include(expected_command) end it "finds repo specific subcommands by searching for a .chef directory" do expected_command = File.join(CHEF_SPEC_DATA, 'knife-site-subcommands', 'plugins', 'knife', 'example_subcommand.rb') - @loader.site_subcommands.should include(expected_command) + expect(@loader.site_subcommands).to include(expected_command) end describe "finding 3rd party plugins" do @@ -79,39 +79,39 @@ describe Chef::Knife::SubcommandLoader do before do env_dup = ENV.to_hash - ENV.stub(:[]).and_return { |key| env_dup[key] } - ENV.stub(:[]).with("HOME").and_return(env_home) + allow(ENV).to receive(:[]) { |key| env_dup[key] } + allow(ENV).to receive(:[]).with("HOME").and_return(env_home) end context "when there is not a ~/.chef/plugin_manifest.json file" do before do - File.stub(:exist?).with(manifest_path).and_return(false) + allow(File).to receive(:exist?).with(manifest_path).and_return(false) end it "searches rubygems for plugins" do if Gem::Specification.respond_to?(:latest_specs) - Gem::Specification.should_receive(:latest_specs).and_call_original + expect(Gem::Specification).to receive(:latest_specs).and_call_original else - Gem.source_index.should_receive(:latest_specs).and_call_original + expect(Gem.source_index).to receive(:latest_specs).and_call_original end @loader.subcommand_files.each do |require_path| - require_path.should match(/chef\/knife\/.*|plugins\/knife\/.*/) + expect(require_path).to match(/chef\/knife\/.*|plugins\/knife\/.*/) end end context "and HOME environment variable is not set" do before do - ENV.stub(:[]).with("HOME").and_return(nil) + allow(ENV).to receive(:[]).with("HOME").and_return(nil) end it "searches rubygems for plugins" do if Gem::Specification.respond_to?(:latest_specs) - Gem::Specification.should_receive(:latest_specs).and_call_original + expect(Gem::Specification).to receive(:latest_specs).and_call_original else - Gem.source_index.should_receive(:latest_specs).and_call_original + expect(Gem.source_index).to receive(:latest_specs).and_call_original end @loader.subcommand_files.each do |require_path| - require_path.should match(/chef\/knife\/.*|plugins\/knife\/.*/) + expect(require_path).to match(/chef\/knife\/.*|plugins\/knife\/.*/) end end end @@ -135,13 +135,13 @@ describe Chef::Knife::SubcommandLoader do let(:manifest_json) { Chef::JSONCompat.to_json(manifest_content) } before do - File.stub(:exist?).with(manifest_path).and_return(true) - File.stub(:read).with(manifest_path).and_return(manifest_json) + allow(File).to receive(:exist?).with(manifest_path).and_return(true) + allow(File).to receive(:read).with(manifest_path).and_return(manifest_json) end it "uses paths from the manifest instead of searching gems" do - Gem::Specification.should_not_receive(:latest_specs).and_call_original - @loader.subcommand_files.should include(ec2_server_create_plugin) + expect(Gem::Specification).not_to receive(:latest_specs).and_call_original + expect(@loader.subcommand_files).to include(ec2_server_create_plugin) end end diff --git a/spec/unit/knife/core/ui_spec.rb b/spec/unit/knife/core/ui_spec.rb index ed1037ebd5..83fff4c082 100644 --- a/spec/unit/knife/core/ui_spec.rb +++ b/spec/unit/knife/core/ui_spec.rb @@ -67,16 +67,16 @@ describe Chef::Knife::UI do @ui.config[:disable_editing] = false @ui.config[:editor] = my_editor @mock = double('Tempfile') - @mock.should_receive(:sync=).with(true) - @mock.should_receive(:puts).with(json_from_ruby) - @mock.should_receive(:close) - @mock.should_receive(:path).at_least(:once).and_return(temp_path) - Tempfile.should_receive(:open).with([ 'knife-edit-', '.json' ]).and_yield(@mock) + expect(@mock).to receive(:sync=).with(true) + expect(@mock).to receive(:puts).with(json_from_ruby) + expect(@mock).to receive(:close) + expect(@mock).to receive(:path).at_least(:once).and_return(temp_path) + expect(Tempfile).to receive(:open).with([ 'knife-edit-', '.json' ]).and_yield(@mock) end context "and the editor works" do before do - @ui.should_receive(:system).with("#{my_editor} #{temp_path}").and_return(true) - IO.should_receive(:read).with(temp_path).and_return(json_from_editor) + expect(@ui).to receive(:system).with("#{my_editor} #{temp_path}").and_return(true) + expect(IO).to receive(:read).with(temp_path).and_return(json_from_editor) end context "when parse_output is false" do @@ -93,8 +93,8 @@ describe Chef::Knife::UI do end context "when running the editor fails with nil" do before do - @ui.should_receive(:system).with("#{my_editor} #{temp_path}").and_return(nil) - IO.should_not_receive(:read) + expect(@ui).to receive(:system).with("#{my_editor} #{temp_path}").and_return(nil) + expect(IO).not_to receive(:read) end it "throws an exception" do expect{ subject }.to raise_error(RuntimeError) @@ -102,8 +102,8 @@ describe Chef::Knife::UI do end context "when running the editor fails with false" do before do - @ui.should_receive(:system).with("#{my_editor} #{temp_path}").and_return(false) - IO.should_not_receive(:read) + expect(@ui).to receive(:system).with("#{my_editor} #{temp_path}").and_return(false) + expect(IO).not_to receive(:read) end it "throws an exception" do expect{ subject }.to raise_error(RuntimeError) @@ -115,13 +115,13 @@ describe Chef::Knife::UI do @ui.config[:disable_editing] = false @ui.config[:editor] = my_editor @tempfile = Tempfile.new([ 'knife-edit-', '.json' ]) - Tempfile.should_receive(:open).with([ 'knife-edit-', '.json' ]).and_yield(@tempfile) + expect(Tempfile).to receive(:open).with([ 'knife-edit-', '.json' ]).and_yield(@tempfile) end context "and the editor works" do before do - @ui.should_receive(:system).with("#{my_editor} #{@tempfile.path}").and_return(true) - IO.should_receive(:read).with(@tempfile.path).and_return(json_from_editor) + expect(@ui).to receive(:system).with("#{my_editor} #{@tempfile.path}").and_return(true) + expect(IO).to receive(:read).with(@tempfile.path).and_return(json_from_editor) end context "when parse_output is false" do @@ -153,33 +153,33 @@ describe Chef::Knife::UI do describe "format_list_for_display" do it "should print the full hash if --with-uri is true" do @ui.config[:with_uri] = true - @ui.format_list_for_display({ :marcy => :playground }).should == { :marcy => :playground } + expect(@ui.format_list_for_display({ :marcy => :playground })).to eq({ :marcy => :playground }) end it "should print only the keys if --with-uri is false" do @ui.config[:with_uri] = false - @ui.format_list_for_display({ :marcy => :playground }).should == [ :marcy ] + expect(@ui.format_list_for_display({ :marcy => :playground })).to eq([ :marcy ]) end end shared_examples "an output mehthod handling IO exceptions" do |method| it "should throw Errno::EIO exceptions" do - @out.stub(:puts).and_raise(Errno::EIO) - @err.stub(:puts).and_raise(Errno::EIO) - lambda {@ui.send(method, "hi")}.should raise_error(Errno::EIO) + allow(@out).to receive(:puts).and_raise(Errno::EIO) + allow(@err).to receive(:puts).and_raise(Errno::EIO) + expect {@ui.send(method, "hi")}.to raise_error(Errno::EIO) end it "should ignore Errno::EPIPE exceptions (CHEF-3516)" do - @out.stub(:puts).and_raise(Errno::EPIPE) - @err.stub(:puts).and_raise(Errno::EPIPE) - lambda {@ui.send(method, "hi")}.should raise_error(SystemExit) + allow(@out).to receive(:puts).and_raise(Errno::EPIPE) + allow(@err).to receive(:puts).and_raise(Errno::EPIPE) + expect {@ui.send(method, "hi")}.to raise_error(SystemExit) end it "should throw Errno::EPIPE exceptions with -VV (CHEF-3516)" do @config[:verbosity] = 2 - @out.stub(:puts).and_raise(Errno::EPIPE) - @err.stub(:puts).and_raise(Errno::EPIPE) - lambda {@ui.send(method, "hi")}.should raise_error(Errno::EPIPE) + allow(@out).to receive(:puts).and_raise(Errno::EPIPE) + allow(@err).to receive(:puts).and_raise(Errno::EPIPE) + expect {@ui.send(method, "hi")}.to raise_error(Errno::EPIPE) end end @@ -188,12 +188,12 @@ describe Chef::Knife::UI do it "formats strings appropriately" do @ui.output("hi") - @out.string.should == "hi\n" + expect(@out.string).to eq("hi\n") end it "formats hashes appropriately" do @ui.output({'hi' => 'a', 'lo' => 'b' }) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM hi: a lo: b EOM @@ -201,12 +201,12 @@ EOM it "formats empty hashes appropriately" do @ui.output({}) - @out.string.should == "\n" + expect(@out.string).to eq("\n") end it "formats arrays appropriately" do @ui.output([ 'a', 'b' ]) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a b EOM @@ -214,22 +214,22 @@ EOM it "formats empty arrays appropriately" do @ui.output([ ]) - @out.string.should == "\n" + expect(@out.string).to eq("\n") end it "formats single-member arrays appropriately" do @ui.output([ 'a' ]) - @out.string.should == "a\n" + expect(@out.string).to eq("a\n") end it "formats nested single-member arrays appropriately" do @ui.output([ [ 'a' ] ]) - @out.string.should == "a\n" + expect(@out.string).to eq("a\n") end it "formats nested arrays appropriately" do @ui.output([ [ 'a', 'b' ], [ 'c', 'd' ]]) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a b @@ -240,7 +240,7 @@ EOM it "formats nested arrays with single- and empty subarrays appropriately" do @ui.output([ [ 'a', 'b' ], [ 'c' ], [], [ 'd', 'e' ]]) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a b @@ -254,7 +254,7 @@ EOM it "formats arrays of hashes with extra lines in between for readability" do @ui.output([ { 'a' => 'b', 'c' => 'd' }, { 'x' => 'y' }, { 'm' => 'n', 'o' => 'p' }]) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a: b c: d @@ -267,7 +267,7 @@ EOM it "formats hashes with empty array members appropriately" do @ui.output({ 'a' => [], 'b' => 'c' }) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a: b: c EOM @@ -275,7 +275,7 @@ EOM it "formats hashes with single-member array values appropriately" do @ui.output({ 'a' => [ 'foo' ], 'b' => 'c' }) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a: foo b: c EOM @@ -283,7 +283,7 @@ EOM it "formats hashes with array members appropriately" do @ui.output({ 'a' => [ 'foo', 'bar' ], 'b' => 'c' }) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a: foo bar @@ -293,7 +293,7 @@ EOM it "formats hashes with single-member nested array values appropriately" do @ui.output({ 'a' => [ [ 'foo' ] ], 'b' => 'c' }) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a: foo b: c @@ -304,12 +304,12 @@ EOM @ui.output({ 'a' => [ [ 'foo', 'bar' ], [ 'baz', 'bjork' ] ], 'b' => 'c' }) # XXX: using a HEREDOC at this point results in a line with required spaces which auto-whitespace removal settings # on editors will remove and will break this test. - @out.string.should == "a:\n foo\n bar\n \n baz\n bjork\nb: c\n" + expect(@out.string).to eq("a:\n foo\n bar\n \n baz\n bjork\nb: c\n") end it "formats hashes with hash values appropriately" do @ui.output({ 'a' => { 'aa' => 'bb', 'cc' => 'dd' }, 'b' => 'c' }) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a: aa: bb cc: dd @@ -319,7 +319,7 @@ EOM it "formats hashes with empty hash values appropriately" do @ui.output({ 'a' => { }, 'b' => 'c' }) - @out.string.should == <<EOM + expect(@out.string).to eq <<EOM a: b: c EOM @@ -341,20 +341,20 @@ EOM describe "format_for_display" do it "should return the raw data" do input = { :gi => :go } - @ui.format_for_display(input).should == input + expect(@ui.format_for_display(input)).to eq(input) end describe "with --attribute passed" do it "should return the deeply nested attribute" do input = { "gi" => { "go" => "ge" }, "id" => "sample-data-bag-item" } @ui.config[:attribute] = "gi.go" - @ui.format_for_display(input).should == { "sample-data-bag-item" => { "gi.go" => "ge" } } + expect(@ui.format_for_display(input)).to eq({ "sample-data-bag-item" => { "gi.go" => "ge" } }) end it "should return multiple attributes" do input = { "gi" => "go", "hi" => "ho", "id" => "sample-data-bag-item" } @ui.config[:attribute] = ["gi", "hi"] - @ui.format_for_display(input).should == { "sample-data-bag-item" => { "gi" => "go", "hi"=> "ho" } } + expect(@ui.format_for_display(input)).to eq({ "sample-data-bag-item" => { "gi" => "go", "hi"=> "ho" } }) end end @@ -365,8 +365,8 @@ EOM input.run_list("role[monkey]", "role[churchmouse]") @ui.config[:run_list] = true response = @ui.format_for_display(input) - response["sample-node"]["run_list"][0].should == "role[monkey]" - response["sample-node"]["run_list"][1].should == "role[churchmouse]" + expect(response["sample-node"]["run_list"][0]).to eq("role[monkey]") + expect(response["sample-node"]["run_list"][1]).to eq("role[churchmouse]") end end end @@ -388,7 +388,7 @@ EOM it "should return an array of the cookbooks with versions" do expected_response = [ "cookbook_name 3.0.0 2.0.0 1.0.0" ] response = @ui.format_cookbook_list_for_display(@item) - response.should == expected_response + expect(response).to eq(expected_response) end describe "with --with-uri" do @@ -400,15 +400,15 @@ EOM "3.0.0" => "http://url/cookbooks/3.0.0"} } @ui.config[:with_uri] = true - @ui.format_cookbook_list_for_display(@item).should == response + expect(@ui.format_cookbook_list_for_display(@item)).to eq(response) end end context "when running on Windows" do before(:each) do stdout = double('StringIO', :tty? => true) - @ui.stub(:stdout).and_return(stdout) - Chef::Platform.stub(:windows?) { true } + allow(@ui).to receive(:stdout).and_return(stdout) + allow(Chef::Platform).to receive(:windows?) { true } Chef::Config.reset end @@ -444,36 +444,36 @@ EOM let(:append_instructions) { true } def run_confirm - @ui.stub(:stdout).and_return(stdout) - @ui.stdin.stub(:readline).and_return(answer) + allow(@ui).to receive(:stdout).and_return(stdout) + allow(@ui.stdin).to receive(:readline).and_return(answer) @ui.confirm(question, append_instructions, default_choice) end def run_confirm_without_exit - @ui.stub(:stdout).and_return(stdout) - @ui.stdin.stub(:readline).and_return(answer) + allow(@ui).to receive(:stdout).and_return(stdout) + allow(@ui.stdin).to receive(:readline).and_return(answer) @ui.confirm_without_exit(question, append_instructions, default_choice) end shared_examples_for "confirm with positive answer" do it "confirm should return true" do - run_confirm.should be_true + expect(run_confirm).to be_truthy end it "confirm_without_exit should return true" do - run_confirm_without_exit.should be_true + expect(run_confirm_without_exit).to be_truthy end end shared_examples_for "confirm with negative answer" do it "confirm should exit 3" do - lambda { + expect { run_confirm - }.should raise_error(SystemExit) { |e| e.status.should == 3 } + }.to raise_error(SystemExit) { |e| expect(e.status).to eq(3) } end it "confirm_without_exit should return false" do - run_confirm_without_exit.should be_false + expect(run_confirm_without_exit).to be_falsey end end @@ -482,7 +482,7 @@ EOM it "should show 'Y/n' in the instructions" do run_confirm - output.should include("Y/n") + expect(output).to include("Y/n") end describe "with empty answer" do @@ -503,7 +503,7 @@ EOM it "should show 'y/N' in the instructions" do run_confirm - output.should include("y/N") + expect(output).to include("y/N") end describe "with empty answer" do @@ -538,8 +538,8 @@ EOM describe "with --y or --yes passed" do it "should return true" do @ui.config[:yes] = true - run_confirm.should be_true - output.should eq("") + expect(run_confirm).to be_truthy + expect(output).to eq("") end end end @@ -547,18 +547,18 @@ EOM describe "when asking for free-form user input" do it "asks a question and returns the answer provided by the user" do out = StringIO.new - @ui.stub(:stdout).and_return(out) - @ui.stub(:stdin).and_return(StringIO.new("http://mychefserver.example.com\n")) - @ui.ask_question("your chef server URL?").should == "http://mychefserver.example.com" - out.string.should == "your chef server URL?" + allow(@ui).to receive(:stdout).and_return(out) + allow(@ui).to receive(:stdin).and_return(StringIO.new("http://mychefserver.example.com\n")) + expect(@ui.ask_question("your chef server URL?")).to eq("http://mychefserver.example.com") + expect(out.string).to eq("your chef server URL?") end it "suggests a default setting and returns the default when the user's response only contains whitespace" do out = StringIO.new - @ui.stub(:stdout).and_return(out) - @ui.stub(:stdin).and_return(StringIO.new(" \n")) - @ui.ask_question("your chef server URL? ", :default => 'http://localhost:4000').should == "http://localhost:4000" - out.string.should == "your chef server URL? [http://localhost:4000] " + allow(@ui).to receive(:stdout).and_return(out) + allow(@ui).to receive(:stdin).and_return(StringIO.new(" \n")) + expect(@ui.ask_question("your chef server URL? ", :default => 'http://localhost:4000')).to eq("http://localhost:4000") + expect(out.string).to eq("your chef server URL? [http://localhost:4000] ") end end diff --git a/spec/unit/knife/data_bag_from_file_spec.rb b/spec/unit/knife/data_bag_from_file_spec.rb index 8de046e7a4..3882bff349 100644 --- a/spec/unit/knife/data_bag_from_file_spec.rb +++ b/spec/unit/knife/data_bag_from_file_spec.rb @@ -26,7 +26,7 @@ Chef::Knife::DataBagFromFile.load_deps describe Chef::Knife::DataBagFromFile do before :each do - Chef::Platform.stub(:windows?) { false } + allow(Chef::Platform).to receive(:windows?) { false } Chef::Config[:node_name] = "webmonkey.example.com" FileUtils.mkdir_p([db_folder, db_folder2]) db_file.write(Chef::JSONCompat.to_json(plain_data)) diff --git a/spec/unit/knife/environment_compare_spec.rb b/spec/unit/knife/environment_compare_spec.rb index 3606b617a9..6d4d3ead52 100644 --- a/spec/unit/knife/environment_compare_spec.rb +++ b/spec/unit/knife/environment_compare_spec.rb @@ -27,21 +27,21 @@ describe Chef::Knife::EnvironmentCompare do "citm" => "http://localhost:4000/environments/citm" } - @knife.stub(:environment_list).and_return(@environments) + allow(@knife).to receive(:environment_list).and_return(@environments) @constraints = { "cita" => { "foo" => "= 1.0.1", "bar" => "= 0.0.4" }, "citm" => { "foo" => "= 1.0.1", "bar" => "= 0.0.2" } } - @knife.stub(:constraint_list).and_return(@constraints) + allow(@knife).to receive(:constraint_list).and_return(@constraints) @cookbooks = { "foo"=>"= 1.0.1", "bar"=>"= 0.0.1" } - @knife.stub(:cookbook_list).and_return(@cookbooks) + allow(@knife).to receive(:cookbook_list).and_return(@cookbooks) @rest_double = double('rest') - @knife.stub(:rest).and_return(@rest_double) + allow(@knife).to receive(:rest).and_return(@rest_double) @cookbook_names = ['apache2', 'mysql', 'foo', 'bar', 'dummy', 'chef_handler'] @base_url = 'https://server.example.com/cookbooks' @cookbook_data = {} @@ -51,10 +51,10 @@ describe Chef::Knife::EnvironmentCompare do 'url' => "#{@base_url}/#{item}/1.0.1"}]} end - @rest_double.stub(:get_rest).with("/cookbooks?num_versions=1").and_return(@cookbook_data) + allow(@rest_double).to receive(:get_rest).with("/cookbooks?num_versions=1").and_return(@cookbook_data) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe 'run' do @@ -62,14 +62,14 @@ describe Chef::Knife::EnvironmentCompare do @knife.config[:format] = 'summary' @knife.run @environments.each do |item, url| - @stdout.string.should match /#{item}/ and @stdout.string.lines.count.should be 4 + expect(@stdout.string).to match /#{item}/ and expect(@stdout.string.lines.count).to be 4 end end it 'should display 4 number of lines' do @knife.config[:format] = 'summary' @knife.run - @stdout.string.lines.count.should be 4 + expect(@stdout.string.lines.count).to be 4 end end @@ -79,7 +79,7 @@ describe Chef::Knife::EnvironmentCompare do @knife.config[:mismatch] = true @knife.run @constraints.each do |item, ver| - @stdout.string.should match /#{ver[1]}/ + expect(@stdout.string).to match /#{ver[1]}/ end end @@ -87,7 +87,7 @@ describe Chef::Knife::EnvironmentCompare do @knife.config[:format] = 'summary' @knife.config[:mismatch] = true @knife.run - @stdout.string.lines.count.should be 3 + expect(@stdout.string.lines.count).to be 3 end end @@ -97,7 +97,7 @@ describe Chef::Knife::EnvironmentCompare do @knife.config[:all] = true @knife.run @constraints.each do |item, ver| - @stdout.string.should match /#{ver[1]}/ + expect(@stdout.string).to match /#{ver[1]}/ end end @@ -105,7 +105,7 @@ describe Chef::Knife::EnvironmentCompare do @knife.config[:format] = 'summary' @knife.config[:all] = true @knife.run - @stdout.string.lines.count.should be 8 + expect(@stdout.string.lines.count).to be 8 end end diff --git a/spec/unit/knife/environment_create_spec.rb b/spec/unit/knife/environment_create_spec.rb index 81bf6731b7..04e45048ef 100644 --- a/spec/unit/knife/environment_create_spec.rb +++ b/spec/unit/knife/environment_create_spec.rb @@ -21,49 +21,49 @@ require 'spec_helper' describe Chef::Knife::EnvironmentCreate do before(:each) do @knife = Chef::Knife::EnvironmentCreate.new - @knife.stub(:msg).and_return true - @knife.stub(:output).and_return true - @knife.stub(:show_usage).and_return true + allow(@knife).to receive(:msg).and_return true + allow(@knife).to receive(:output).and_return true + allow(@knife).to receive(:show_usage).and_return true @knife.name_args = [ "production" ] @environment = Chef::Environment.new - @environment.stub(:save) + allow(@environment).to receive(:save) - Chef::Environment.stub(:new).and_return @environment - @knife.stub(:edit_data).and_return @environment + allow(Chef::Environment).to receive(:new).and_return @environment + allow(@knife).to receive(:edit_data).and_return @environment end describe "run" do it "should create a new environment" do - Chef::Environment.should_receive(:new) + expect(Chef::Environment).to receive(:new) @knife.run end it "should set the environment name" do - @environment.should_receive(:name).with("production") + expect(@environment).to receive(:name).with("production") @knife.run end it "should not print the environment" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end it "should prompt you to edit the data" do - @knife.should_receive(:edit_data).with(@environment) + expect(@knife).to receive(:edit_data).with(@environment) @knife.run end it "should save the environment" do - @environment.should_receive(:save) + expect(@environment).to receive(:save) @knife.run end it "should show usage and exit when no environment name is provided" do @knife.name_args = [ ] - @knife.ui.should_receive(:fatal) - @knife.should_receive(:show_usage) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:fatal) + expect(@knife).to receive(:show_usage) + expect { @knife.run }.to raise_error(SystemExit) end describe "with --description" do @@ -72,7 +72,7 @@ describe Chef::Knife::EnvironmentCreate do end it "should set the description" do - @environment.should_receive(:description).with("This is production") + expect(@environment).to receive(:description).with("This is production") @knife.run end end @@ -83,7 +83,7 @@ describe Chef::Knife::EnvironmentCreate do end it "should pretty print the environment, formatted for display" do - @knife.should_receive(:output).with(@environment) + expect(@knife).to receive(:output).with(@environment) @knife.run end end diff --git a/spec/unit/knife/environment_delete_spec.rb b/spec/unit/knife/environment_delete_spec.rb index 0f6b5f3272..95df6e15fe 100644 --- a/spec/unit/knife/environment_delete_spec.rb +++ b/spec/unit/knife/environment_delete_spec.rb @@ -21,50 +21,50 @@ require 'spec_helper' describe Chef::Knife::EnvironmentDelete do before(:each) do @knife = Chef::Knife::EnvironmentDelete.new - @knife.stub(:msg).and_return true - @knife.stub(:output).and_return true - @knife.stub(:show_usage).and_return true - @knife.stub(:confirm).and_return true + allow(@knife).to receive(:msg).and_return true + allow(@knife).to receive(:output).and_return true + allow(@knife).to receive(:show_usage).and_return true + allow(@knife).to receive(:confirm).and_return true @knife.name_args = [ "production" ] @environment = Chef::Environment.new @environment.name("production") @environment.description("Please delete me") - @environment.stub(:destroy).and_return true - Chef::Environment.stub(:load).and_return @environment + allow(@environment).to receive(:destroy).and_return true + allow(Chef::Environment).to receive(:load).and_return @environment end it "should confirm that you want to delete" do - @knife.should_receive(:confirm) + expect(@knife).to receive(:confirm) @knife.run end it "should load the environment" do - Chef::Environment.should_receive(:load).with("production") + expect(Chef::Environment).to receive(:load).with("production") @knife.run end it "should delete the environment" do - @environment.should_receive(:destroy) + expect(@environment).to receive(:destroy) @knife.run end it "should not print the environment" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end it "should show usage and exit when no environment name is provided" do @knife.name_args = [] - @knife.ui.should_receive(:fatal) - @knife.should_receive(:show_usage) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:fatal) + expect(@knife).to receive(:show_usage) + expect { @knife.run }.to raise_error(SystemExit) end describe "with --print-after" do it "should pretty print the environment, formatted for display" do @knife.config[:print_after] = true - @knife.should_receive(:output).with(@environment) + expect(@knife).to receive(:output).with(@environment) @knife.run end end diff --git a/spec/unit/knife/environment_edit_spec.rb b/spec/unit/knife/environment_edit_spec.rb index a82ead0b6b..61c2663a41 100644 --- a/spec/unit/knife/environment_edit_spec.rb +++ b/spec/unit/knife/environment_edit_spec.rb @@ -21,26 +21,26 @@ require 'spec_helper' describe Chef::Knife::EnvironmentEdit do before(:each) do @knife = Chef::Knife::EnvironmentEdit.new - @knife.ui.stub(:msg).and_return true - @knife.ui.stub(:output).and_return true - @knife.ui.stub(:show_usage).and_return true + allow(@knife.ui).to receive(:msg).and_return true + allow(@knife.ui).to receive(:output).and_return true + allow(@knife.ui).to receive(:show_usage).and_return true @knife.name_args = [ "production" ] @environment = Chef::Environment.new @environment.name("production") @environment.description("Please edit me") - @environment.stub(:save).and_return true - Chef::Environment.stub(:load).and_return @environment - @knife.ui.stub(:edit_data).and_return @environment + allow(@environment).to receive(:save).and_return true + allow(Chef::Environment).to receive(:load).and_return @environment + allow(@knife.ui).to receive(:edit_data).and_return @environment end it "should load the environment" do - Chef::Environment.should_receive(:load).with("production") + expect(Chef::Environment).to receive(:load).with("production") @knife.run end it "should let you edit the environment" do - @knife.ui.should_receive(:edit_data).with(@environment) + expect(@knife.ui).to receive(:edit_data).with(@environment) @knife.run end @@ -48,31 +48,31 @@ describe Chef::Knife::EnvironmentEdit do pansy = Chef::Environment.new @environment.name("new_environment_name") - @knife.ui.should_receive(:edit_data).with(@environment).and_return(pansy) - pansy.should_receive(:save) + expect(@knife.ui).to receive(:edit_data).with(@environment).and_return(pansy) + expect(pansy).to receive(:save) @knife.run end it "should not save the unedited environment data" do - @environment.should_not_receive(:save) + expect(@environment).not_to receive(:save) @knife.run end it "should not print the environment" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end it "shoud show usage and exit when no environment name is provided" do @knife.name_args = [] - @knife.should_receive(:show_usage) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect { @knife.run }.to raise_error(SystemExit) end describe "with --print-after" do it "should pretty print the environment, formatted for display" do @knife.config[:print_after] = true - @knife.ui.should_receive(:output).with(@environment) + expect(@knife.ui).to receive(:output).with(@environment) @knife.run end end diff --git a/spec/unit/knife/environment_from_file_spec.rb b/spec/unit/knife/environment_from_file_spec.rb index 562e7f8cf5..d150e5ee64 100644 --- a/spec/unit/knife/environment_from_file_spec.rb +++ b/spec/unit/knife/environment_from_file_spec.rb @@ -23,24 +23,24 @@ Chef::Knife::EnvironmentFromFile.load_deps describe Chef::Knife::EnvironmentFromFile do before(:each) do - Chef::Platform.stub(:windows?) { false } + allow(Chef::Platform).to receive(:windows?) { false } @knife = Chef::Knife::EnvironmentFromFile.new @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) @knife.name_args = [ "spec.rb" ] @environment = Chef::Environment.new @environment.name("spec") @environment.description("runs the unit tests") @environment.cookbook_versions({"apt" => "= 1.2.3"}) - @environment.stub(:save).and_return true - @knife.loader.stub(:load_from).and_return @environment + allow(@environment).to receive(:save).and_return true + allow(@knife.loader).to receive(:load_from).and_return @environment end describe "run" do it "loads the environment data from a file and saves it" do - @knife.loader.should_receive(:load_from).with('environments', 'spec.rb').and_return(@environment) - @environment.should_receive(:save) + expect(@knife.loader).to receive(:load_from).with('environments', 'spec.rb').and_return(@environment) + expect(@environment).to receive(:save) @knife.run end @@ -48,41 +48,41 @@ describe Chef::Knife::EnvironmentFromFile do before(:each) do @env_apple = @environment.dup @env_apple.name("apple") - @knife.loader.stub(:load_from).with("apple.rb").and_return @env_apple + allow(@knife.loader).to receive(:load_from).with("apple.rb").and_return @env_apple end it "loads multiple environments if given" do @knife.name_args = [ "spec.rb", "apple.rb" ] - @environment.should_receive(:save).twice + expect(@environment).to receive(:save).twice @knife.run end it "loads all environments with -a" do - File.stub(:expand_path).with("./environments/").and_return("/tmp/environments") - Dir.stub(:glob).with("/tmp/environments/*.{json,rb}").and_return(["spec.rb", "apple.rb"]) + allow(File).to receive(:expand_path).with("./environments/").and_return("/tmp/environments") + allow(Dir).to receive(:glob).with("/tmp/environments/*.{json,rb}").and_return(["spec.rb", "apple.rb"]) @knife.name_args = [] - @knife.stub(:config).and_return({:all => true}) - @environment.should_receive(:save).twice + allow(@knife).to receive(:config).and_return({:all => true}) + expect(@environment).to receive(:save).twice @knife.run end end it "should not print the environment" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end it "should show usage and exit if not filename is provided" do @knife.name_args = [] - @knife.ui.should_receive(:fatal) - @knife.should_receive(:show_usage) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:fatal) + expect(@knife).to receive(:show_usage) + expect { @knife.run }.to raise_error(SystemExit) end describe "with --print-after" do it "should pretty print the environment, formatted for display" do @knife.config[:print_after] = true - @knife.should_receive(:output) + expect(@knife).to receive(:output) @knife.run end end diff --git a/spec/unit/knife/environment_list_spec.rb b/spec/unit/knife/environment_list_spec.rb index 25d2714d23..6488a073b6 100644 --- a/spec/unit/knife/environment_list_spec.rb +++ b/spec/unit/knife/environment_list_spec.rb @@ -21,33 +21,33 @@ require 'spec_helper' describe Chef::Knife::EnvironmentList do before(:each) do @knife = Chef::Knife::EnvironmentList.new - @knife.stub(:msg).and_return true - @knife.stub(:output).and_return true - @knife.stub(:show_usage).and_return true + allow(@knife).to receive(:msg).and_return true + allow(@knife).to receive(:output).and_return true + allow(@knife).to receive(:show_usage).and_return true @environments = { "production" => "http://localhost:4000/environments/production", "development" => "http://localhost:4000/environments/development", "testing" => "http://localhost:4000/environments/testing" } - Chef::Environment.stub(:list).and_return @environments + allow(Chef::Environment).to receive(:list).and_return @environments end it "should make an api call to list the environments" do - Chef::Environment.should_receive(:list) + expect(Chef::Environment).to receive(:list) @knife.run end it "should print the environment names in a sorted list" do names = @environments.keys.sort { |a,b| a <=> b } - @knife.should_receive(:output).with(names) + expect(@knife).to receive(:output).with(names) @knife.run end describe "with --with-uri" do it "should print and unsorted list of the environments and their URIs" do @knife.config[:with_uri] = true - @knife.should_receive(:output).with(@environments) + expect(@knife).to receive(:output).with(@environments) @knife.run end end diff --git a/spec/unit/knife/environment_show_spec.rb b/spec/unit/knife/environment_show_spec.rb index c7b0c21657..caac958f8e 100644 --- a/spec/unit/knife/environment_show_spec.rb +++ b/spec/unit/knife/environment_show_spec.rb @@ -21,32 +21,32 @@ require 'spec_helper' describe Chef::Knife::EnvironmentShow do before(:each) do @knife = Chef::Knife::EnvironmentShow.new - @knife.stub(:msg).and_return true - @knife.stub(:output).and_return true - @knife.stub(:show_usage).and_return true + allow(@knife).to receive(:msg).and_return true + allow(@knife).to receive(:output).and_return true + allow(@knife).to receive(:show_usage).and_return true @knife.name_args = [ "production" ] @environment = Chef::Environment.new @environment.name("production") @environment.description("Look at me!") - Chef::Environment.stub(:load).and_return @environment + allow(Chef::Environment).to receive(:load).and_return @environment end it "should load the environment" do - Chef::Environment.should_receive(:load).with("production") + expect(Chef::Environment).to receive(:load).with("production") @knife.run end it "should pretty print the environment, formatted for display" do - @knife.should_receive(:format_for_display).with(@environment) - @knife.should_receive(:output) + expect(@knife).to receive(:format_for_display).with(@environment) + expect(@knife).to receive(:output) @knife.run end it "should show usage and exit when no environment name is provided" do @knife.name_args = [] - @knife.ui.should_receive(:fatal) - @knife.should_receive(:show_usage) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:fatal) + expect(@knife).to receive(:show_usage) + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/index_rebuild_spec.rb b/spec/unit/knife/index_rebuild_spec.rb index 3a8ec00651..6c3b60bd88 100644 --- a/spec/unit/knife/index_rebuild_spec.rb +++ b/spec/unit/knife/index_rebuild_spec.rb @@ -24,18 +24,18 @@ describe Chef::Knife::IndexRebuild do let(:rest_client){double(Chef::REST)} let(:stub_rest!) do - knife.should_receive(:rest).and_return(rest_client) + expect(knife).to receive(:rest).and_return(rest_client) end before :each do # This keeps the test output clean - knife.ui.stub(:stdout).and_return(StringIO.new) + allow(knife.ui).to receive(:stdout).and_return(StringIO.new) end context "#grab_api_info" do let(:http_not_found_response) do e = Net::HTTPNotFound.new("1.1", 404, "blah") - e.stub(:[]).with("x-ops-api-info").and_return(api_header_value) + allow(e).to receive(:[]).with("x-ops-api-info").and_return(api_header_value) e end @@ -45,20 +45,20 @@ describe Chef::Knife::IndexRebuild do before(:each) do stub_rest! - rest_client.stub(:get_rest).and_raise(http_server_exception) + allow(rest_client).to receive(:get_rest).and_raise(http_server_exception) end context "against a Chef 11 server" do let(:api_header_value){"flavor=osc;version=11.0.0;erchef=1.2.3"} it "retrieves API information" do - knife.grab_api_info.should == {"flavor" => "osc", "version" => "11.0.0", "erchef" => "1.2.3"} + expect(knife.grab_api_info).to eq({"flavor" => "osc", "version" => "11.0.0", "erchef" => "1.2.3"}) end end # Chef 11 context "against a Chef 10 server" do let(:api_header_value){nil} it "finds no API information" do - knife.grab_api_info.should == {} + expect(knife.grab_api_info).to eq({}) end end # Chef 10 end # grab_api_info @@ -66,18 +66,18 @@ describe Chef::Knife::IndexRebuild do context "#unsupported_version?" do context "with Chef 11 API metadata" do it "is unsupported" do - knife.unsupported_version?({"version" => "11.0.0", "flavor" => "osc", "erchef" => "1.2.3"}).should be_true + expect(knife.unsupported_version?({"version" => "11.0.0", "flavor" => "osc", "erchef" => "1.2.3"})).to be_truthy end it "only truly relies on the version being non-nil" do - knife.unsupported_version?({"version" => "1", "flavor" => "osc", "erchef" => "1.2.3"}).should be_true + expect(knife.unsupported_version?({"version" => "1", "flavor" => "osc", "erchef" => "1.2.3"})).to be_truthy end end context "with Chef 10 API metadata" do it "is supported" do # Chef 10 will have no metadata - knife.unsupported_version?({}).should be_false + expect(knife.unsupported_version?({})).to be_falsey end end end # unsupported_version? @@ -85,7 +85,7 @@ describe Chef::Knife::IndexRebuild do context "Simulating a 'knife index rebuild' run" do before :each do - knife.should_receive(:grab_api_info).and_return(api_info) + expect(knife).to receive(:grab_api_info).and_return(api_info) server_specific_stubs! end @@ -97,8 +97,8 @@ describe Chef::Knife::IndexRebuild do } end let(:server_specific_stubs!) do - knife.should_receive(:unsupported_server_message).with(api_info) - knife.should_receive(:exit).with(1) + expect(knife).to receive(:unsupported_server_message).with(api_info) + expect(knife).to receive(:exit).with(1) end it "should not be allowed" do @@ -110,11 +110,11 @@ describe Chef::Knife::IndexRebuild do let(:api_info){ {} } let(:server_specific_stubs!) do stub_rest! - rest_client.should_receive(:post_rest).with("/search/reindex", {}).and_return("representative output") - knife.should_not_receive(:unsupported_server_message) - knife.should_receive(:deprecated_server_message) - knife.should_receive(:nag) - knife.should_receive(:output).with("representative output") + expect(rest_client).to receive(:post_rest).with("/search/reindex", {}).and_return("representative output") + expect(knife).not_to receive(:unsupported_server_message) + expect(knife).to receive(:deprecated_server_message) + expect(knife).to receive(:nag) + expect(knife).to receive(:output).with("representative output") end it "should be allowed" do knife.run diff --git a/spec/unit/knife/knife_help.rb b/spec/unit/knife/knife_help.rb index e66a44801b..293bae17f4 100644 --- a/spec/unit/knife/knife_help.rb +++ b/spec/unit/knife/knife_help.rb @@ -26,66 +26,66 @@ describe Chef::Knife::Help do end it "should return a list of help topics" do - @knife.help_topics.should include("knife-status") + expect(@knife.help_topics).to include("knife-status") end it "should run man for you" do @knife.name_args = [ "shell" ] - @knife.should_receive(:exec).with(/^man \/.*\/shell.1$/) + expect(@knife).to receive(:exec).with(/^man \/.*\/shell.1$/) @knife.run end it "should suggest topics" do @knife.name_args = [ "list" ] - @knife.ui.stub(:msg) - @knife.ui.should_receive(:info).with("Available help topics are: ") - @knife.ui.should_receive(:msg).with(/knife/) - @knife.stub(:exec) - @knife.should_receive(:exit).with(1) + allow(@knife.ui).to receive(:msg) + expect(@knife.ui).to receive(:info).with("Available help topics are: ") + expect(@knife.ui).to receive(:msg).with(/knife/) + allow(@knife).to receive(:exec) + expect(@knife).to receive(:exit).with(1) @knife.run end describe "find_manpage_path" do it "should find the man page in the gem" do - @knife.find_manpage_path("shell").should =~ /distro\/common\/man\/man1\/chef-shell.1$/ + expect(@knife.find_manpage_path("shell")).to match(/distro\/common\/man\/man1\/chef-shell.1$/) end it "should provide the man page name if not in the gem" do - @knife.find_manpage_path("foo").should == "foo" + expect(@knife.find_manpage_path("foo")).to eq("foo") end end describe "find_manpages_for_query" do it "should error if it does not find a match" do - @knife.ui.stub(:error) - @knife.ui.stub(:info) - @knife.ui.stub(:msg) - @knife.should_receive(:exit).with(1) - @knife.ui.should_receive(:error).with("No help found for 'chickens'") - @knife.ui.should_receive(:msg).with(/knife/) + allow(@knife.ui).to receive(:error) + allow(@knife.ui).to receive(:info) + allow(@knife.ui).to receive(:msg) + expect(@knife).to receive(:exit).with(1) + expect(@knife.ui).to receive(:error).with("No help found for 'chickens'") + expect(@knife.ui).to receive(:msg).with(/knife/) @knife.find_manpages_for_query("chickens") end end describe "print_help_topics" do it "should print the known help topics" do - @knife.ui.stub(:msg) - @knife.ui.stub(:info) - @knife.ui.should_receive(:msg).with(/knife/) + allow(@knife.ui).to receive(:msg) + allow(@knife.ui).to receive(:info) + expect(@knife.ui).to receive(:msg).with(/knife/) @knife.print_help_topics end it "should shorten topics prefixed by knife-" do - @knife.ui.stub(:msg) - @knife.ui.stub(:info) - @knife.ui.should_receive(:msg).with(/node/) + allow(@knife.ui).to receive(:msg) + allow(@knife.ui).to receive(:info) + expect(@knife.ui).to receive(:msg).with(/node/) @knife.print_help_topics end it "should not leave topics prefixed by knife-" do - @knife.ui.stub(:msg) - @knife.ui.stub(:info) - @knife.ui.should_not_receive(:msg).with(/knife-node/) + allow(@knife.ui).to receive(:msg) + allow(@knife.ui).to receive(:info) + expect(@knife.ui).not_to receive(:msg).with(/knife-node/) @knife.print_help_topics end end diff --git a/spec/unit/knife/node_bulk_delete_spec.rb b/spec/unit/knife/node_bulk_delete_spec.rb index 3faece5469..57a8d0bf64 100644 --- a/spec/unit/knife/node_bulk_delete_spec.rb +++ b/spec/unit/knife/node_bulk_delete_spec.rb @@ -26,8 +26,8 @@ describe Chef::Knife::NodeBulkDelete do @knife = Chef::Knife::NodeBulkDelete.new @knife.name_args = ["."] @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:confirm).and_return(true) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:confirm).and_return(true) @nodes = Hash.new %w{adam brent jacob}.each do |node_name| @nodes[node_name] = "http://localhost:4000/nodes/#{node_name}" @@ -40,11 +40,11 @@ describe Chef::Knife::NodeBulkDelete do inflatedish[name] = Chef::Node.new.tap {|n| n.name(name)} inflatedish end - Chef::Node.should_receive(:list).and_return(@nodes) + expect(Chef::Node).to receive(:list).and_return(@nodes) # I hate not having == defined for anything :( actual = @knife.all_nodes - actual.keys.should =~ expected.keys - actual.values.map {|n| n.name }.should =~ %w[adam brent jacob] + expect(actual.keys).to match_array(expected.keys) + expect(actual.values.map {|n| n.name }).to match_array(%w[adam brent jacob]) end end @@ -53,41 +53,41 @@ describe Chef::Knife::NodeBulkDelete do @inflatedish_list = @nodes.keys.inject({}) do |nodes_by_name, name| node = Chef::Node.new() node.name(name) - node.stub(:destroy).and_return(true) + allow(node).to receive(:destroy).and_return(true) nodes_by_name[name] = node nodes_by_name end - @knife.stub(:all_nodes).and_return(@inflatedish_list) + allow(@knife).to receive(:all_nodes).and_return(@inflatedish_list) end it "should print the nodes you are about to delete" do @knife.run - @stdout.string.should match(/#{@knife.ui.list(@nodes.keys.sort, :columns_down)}/) + expect(@stdout.string).to match(/#{@knife.ui.list(@nodes.keys.sort, :columns_down)}/) end it "should confirm you really want to delete them" do - @knife.ui.should_receive(:confirm) + expect(@knife.ui).to receive(:confirm) @knife.run end it "should delete each node" do @inflatedish_list.each_value do |n| - n.should_receive(:destroy) + expect(n).to receive(:destroy) end @knife.run end it "should only delete nodes that match the regex" do @knife.name_args = ['adam'] - @inflatedish_list['adam'].should_receive(:destroy) - @inflatedish_list['brent'].should_not_receive(:destroy) - @inflatedish_list['jacob'].should_not_receive(:destroy) + expect(@inflatedish_list['adam']).to receive(:destroy) + expect(@inflatedish_list['brent']).not_to receive(:destroy) + expect(@inflatedish_list['jacob']).not_to receive(:destroy) @knife.run end it "should exit if the regex is not provided" do @knife.name_args = [] - lambda { @knife.run }.should raise_error(SystemExit) + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/node_delete_spec.rb b/spec/unit/knife/node_delete_spec.rb index 04eca389c6..0941d850e5 100644 --- a/spec/unit/knife/node_delete_spec.rb +++ b/spec/unit/knife/node_delete_spec.rb @@ -26,41 +26,41 @@ describe Chef::Knife::NodeDelete do :print_after => nil } @knife.name_args = [ "adam" ] - @knife.stub(:output).and_return(true) - @knife.stub(:confirm).and_return(true) + allow(@knife).to receive(:output).and_return(true) + allow(@knife).to receive(:confirm).and_return(true) @node = Chef::Node.new() - @node.stub(:destroy).and_return(true) - Chef::Node.stub(:load).and_return(@node) + allow(@node).to receive(:destroy).and_return(true) + allow(Chef::Node).to receive(:load).and_return(@node) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe "run" do it "should confirm that you want to delete" do - @knife.should_receive(:confirm) + expect(@knife).to receive(:confirm) @knife.run end it "should load the node" do - Chef::Node.should_receive(:load).with("adam").and_return(@node) + expect(Chef::Node).to receive(:load).with("adam").and_return(@node) @knife.run end it "should delete the node" do - @node.should_receive(:destroy).and_return(@node) + expect(@node).to receive(:destroy).and_return(@node) @knife.run end it "should not print the node" do - @knife.should_not_receive(:output).with("poop") + expect(@knife).not_to receive(:output).with("poop") @knife.run end describe "with -p or --print-after" do it "should pretty print the node, formatted for display" do @knife.config[:print_after] = true - @knife.should_receive(:format_for_display).with(@node).and_return("poop") - @knife.should_receive(:output).with("poop") + expect(@knife).to receive(:format_for_display).with(@node).and_return("poop") + expect(@knife).to receive(:output).with("poop") @knife.run end end diff --git a/spec/unit/knife/node_edit_spec.rb b/spec/unit/knife/node_edit_spec.rb index 27db3416f4..58e2da2a1c 100644 --- a/spec/unit/knife/node_edit_spec.rb +++ b/spec/unit/knife/node_edit_spec.rb @@ -39,13 +39,13 @@ describe Chef::Knife::NodeEdit do end it "should load the node" do - Chef::Node.should_receive(:load).with("adam").and_return(@node) + expect(Chef::Node).to receive(:load).with("adam").and_return(@node) @knife.node end describe "after loading the node" do before do - @knife.stub(:node).and_return(@node) + allow(@knife).to receive(:node).and_return(@node) @node.automatic_attrs = {:go => :away} @node.default_attrs = {:hide => :me} @node.override_attrs = {:dont => :show} @@ -56,37 +56,37 @@ describe Chef::Knife::NodeEdit do it "creates a view of the node without attributes from roles or ohai" do actual = deserialized_json_view - actual.should_not have_key("automatic") - actual.should_not have_key("override") - actual.should_not have_key("default") - actual["normal"].should == {"do_show" => "these"} - actual["run_list"].should == ["recipe[foo]"] - actual["chef_environment"].should == "prod" + expect(actual).not_to have_key("automatic") + expect(actual).not_to have_key("override") + expect(actual).not_to have_key("default") + expect(actual["normal"]).to eq({"do_show" => "these"}) + expect(actual["run_list"]).to eq(["recipe[foo]"]) + expect(actual["chef_environment"]).to eq("prod") end it "shows the extra attributes when given the --all option" do @knife.config[:all_attributes] = true actual = deserialized_json_view - actual["automatic"].should == {"go" => "away"} - actual["override"].should == {"dont" => "show"} - actual["default"].should == {"hide" => "me"} - actual["normal"].should == {"do_show" => "these"} - actual["run_list"].should == ["recipe[foo]"] - actual["chef_environment"].should == "prod" + expect(actual["automatic"]).to eq({"go" => "away"}) + expect(actual["override"]).to eq({"dont" => "show"}) + expect(actual["default"]).to eq({"hide" => "me"}) + expect(actual["normal"]).to eq({"do_show" => "these"}) + expect(actual["run_list"]).to eq(["recipe[foo]"]) + expect(actual["chef_environment"]).to eq("prod") end it "does not consider unedited data updated" do view = deserialized_json_view @knife.node_editor.send(:apply_updates, view) - @knife.node_editor.should_not be_updated + expect(@knife.node_editor).not_to be_updated end it "considers edited data updated" do view = deserialized_json_view view["run_list"] << "role[fuuu]" @knife.node_editor.send(:apply_updates, view) - @knife.node_editor.should be_updated + expect(@knife.node_editor).to be_updated end end @@ -94,7 +94,7 @@ describe Chef::Knife::NodeEdit do describe "edit_node" do before do - @knife.stub(:node).and_return(@node) + allow(@knife).to receive(:node).and_return(@node) end let(:subject) { @knife.node_editor.edit_node } diff --git a/spec/unit/knife/node_environment_set_spec.rb b/spec/unit/knife/node_environment_set_spec.rb index 46ee1fea18..10267915d7 100644 --- a/spec/unit/knife/node_environment_set_spec.rb +++ b/spec/unit/knife/node_environment_set_spec.rb @@ -23,32 +23,32 @@ describe Chef::Knife::NodeEnvironmentSet do Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::NodeEnvironmentSet.new @knife.name_args = [ "adam", "bar" ] - @knife.stub(:output).and_return(true) + allow(@knife).to receive(:output).and_return(true) @node = Chef::Node.new() @node.name("knifetest-node") @node.chef_environment << "foo" - @node.stub(:save).and_return(true) - Chef::Node.stub(:load).and_return(@node) + allow(@node).to receive(:save).and_return(true) + allow(Chef::Node).to receive(:load).and_return(@node) end describe "run" do it "should load the node" do - Chef::Node.should_receive(:load).with("adam") + expect(Chef::Node).to receive(:load).with("adam") @knife.run end it "should update the environment" do @knife.run - @node.chef_environment.should == 'bar' + expect(@node.chef_environment).to eq('bar') end it "should save the node" do - @node.should_receive(:save) + expect(@node).to receive(:save) @knife.run end it "should print the environment" do - @knife.should_receive(:output).and_return(true) + expect(@knife).to receive(:output).and_return(true) @knife.run end @@ -58,13 +58,13 @@ describe Chef::Knife::NodeEnvironmentSet do @stdout = StringIO.new @stderr = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end it "should exit" do @knife.name_args = [ "adam" ] - lambda { @knife.run }.should raise_error SystemExit + expect { @knife.run }.to raise_error SystemExit end it "should show the user the usage and an error" do @@ -72,8 +72,8 @@ describe Chef::Knife::NodeEnvironmentSet do begin ; @knife.run ; rescue SystemExit ; end - @stdout.string.should eq "USAGE: knife node environment set NODE ENVIRONMENT\n" - @stderr.string.should eq "FATAL: You must specify a node name and an environment.\n" + expect(@stdout.string).to eq "USAGE: knife node environment set NODE ENVIRONMENT\n" + expect(@stderr.string).to eq "FATAL: You must specify a node name and an environment.\n" end end end diff --git a/spec/unit/knife/node_from_file_spec.rb b/spec/unit/knife/node_from_file_spec.rb index 56a2a08b68..623904753e 100644 --- a/spec/unit/knife/node_from_file_spec.rb +++ b/spec/unit/knife/node_from_file_spec.rb @@ -28,30 +28,30 @@ describe Chef::Knife::NodeFromFile do :print_after => nil } @knife.name_args = [ "adam.rb" ] - @knife.stub(:output).and_return(true) - @knife.stub(:confirm).and_return(true) + allow(@knife).to receive(:output).and_return(true) + allow(@knife).to receive(:confirm).and_return(true) @node = Chef::Node.new() - @node.stub(:save) - @knife.loader.stub(:load_from).and_return(@node) + allow(@node).to receive(:save) + allow(@knife.loader).to receive(:load_from).and_return(@node) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe "run" do it "should load from a file" do - @knife.loader.should_receive(:load_from).with('nodes', 'adam.rb').and_return(@node) + expect(@knife.loader).to receive(:load_from).with('nodes', 'adam.rb').and_return(@node) @knife.run end it "should not print the Node" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end describe "with -p or --print-after" do it "should print the Node" do @knife.config[:print_after] = true - @knife.should_receive(:output) + expect(@knife).to receive(:output) @knife.run end end diff --git a/spec/unit/knife/node_list_spec.rb b/spec/unit/knife/node_list_spec.rb index cad2d6482d..71edea78f7 100644 --- a/spec/unit/knife/node_list_spec.rb +++ b/spec/unit/knife/node_list_spec.rb @@ -23,38 +23,38 @@ describe Chef::Knife::NodeList do Chef::Config[:node_name] = "webmonkey.example.com" Chef::Config[:environment] = nil # reset this value each time, as it is not reloaded @knife = Chef::Knife::NodeList.new - @knife.stub(:output).and_return(true) + allow(@knife).to receive(:output).and_return(true) @list = { "foo" => "http://example.com/foo", "bar" => "http://example.com/foo" } - Chef::Node.stub(:list).and_return(@list) - Chef::Node.stub(:list_by_environment).and_return(@list) + allow(Chef::Node).to receive(:list).and_return(@list) + allow(Chef::Node).to receive(:list_by_environment).and_return(@list) end describe "run" do it "should list all of the nodes if -E is not specified" do - Chef::Node.should_receive(:list).and_return(@list) + expect(Chef::Node).to receive(:list).and_return(@list) @knife.run end it "should pretty print the list" do - Chef::Node.should_receive(:list).and_return(@list) - @knife.should_receive(:output).with([ "bar", "foo" ]) + expect(Chef::Node).to receive(:list).and_return(@list) + expect(@knife).to receive(:output).with([ "bar", "foo" ]) @knife.run end it "should list nodes in the specific environment if -E ENVIRONMENT is specified" do Chef::Config[:environment] = "prod" - Chef::Node.should_receive(:list_by_environment).with("prod").and_return(@list) + expect(Chef::Node).to receive(:list_by_environment).with("prod").and_return(@list) @knife.run end describe "with -w or --with-uri" do it "should pretty print the hash" do @knife.config[:with_uri] = true - Chef::Node.should_receive(:list).and_return(@list) - @knife.should_receive(:output).with(@list) + expect(Chef::Node).to receive(:list).and_return(@list) + expect(@knife).to receive(:output).with(@list) @knife.run end end diff --git a/spec/unit/knife/node_run_list_add_spec.rb b/spec/unit/knife/node_run_list_add_spec.rb index bd33a359a2..92fbfd23fe 100644 --- a/spec/unit/knife/node_run_list_add_spec.rb +++ b/spec/unit/knife/node_run_list_add_spec.rb @@ -26,30 +26,30 @@ describe Chef::Knife::NodeRunListAdd do :after => nil } @knife.name_args = [ "adam", "role[monkey]" ] - @knife.stub(:output).and_return(true) + allow(@knife).to receive(:output).and_return(true) @node = Chef::Node.new() - @node.stub(:save).and_return(true) - Chef::Node.stub(:load).and_return(@node) + allow(@node).to receive(:save).and_return(true) + allow(Chef::Node).to receive(:load).and_return(@node) end describe "run" do it "should load the node" do - Chef::Node.should_receive(:load).with("adam") + expect(Chef::Node).to receive(:load).with("adam") @knife.run end it "should add to the run list" do @knife.run - @node.run_list[0].should == 'role[monkey]' + expect(@node.run_list[0]).to eq('role[monkey]') end it "should save the node" do - @node.should_receive(:save) + expect(@node).to receive(:save) @knife.run end it "should print the run list" do - @knife.should_receive(:output).and_return(true) + expect(@knife).to receive(:output).and_return(true) @knife.run end @@ -59,9 +59,9 @@ describe Chef::Knife::NodeRunListAdd do @node.run_list << "role[barn]" @knife.config[:after] = "role[acorns]" @knife.run - @node.run_list[0].should == "role[acorns]" - @node.run_list[1].should == "role[monkey]" - @node.run_list[2].should == "role[barn]" + expect(@node.run_list[0]).to eq("role[acorns]") + expect(@node.run_list[1]).to eq("role[monkey]") + expect(@node.run_list[2]).to eq("role[barn]") end end @@ -71,9 +71,9 @@ describe Chef::Knife::NodeRunListAdd do @node.run_list << "role[barn]" @knife.config[:before] = "role[acorns]" @knife.run - @node.run_list[0].should == "role[monkey]" - @node.run_list[1].should == "role[acorns]" - @node.run_list[2].should == "role[barn]" + expect(@node.run_list[0]).to eq("role[monkey]") + expect(@node.run_list[1]).to eq("role[acorns]") + expect(@node.run_list[2]).to eq("role[barn]") end end @@ -83,8 +83,8 @@ describe Chef::Knife::NodeRunListAdd do @node.run_list << "role[barn]" @knife.config[:before] = "role[acorns]" @knife.config[:after] = "role[acorns]" - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end @@ -93,9 +93,9 @@ describe Chef::Knife::NodeRunListAdd do @knife.name_args = [ "adam", "role[monkey],role[duck]" ] @node.run_list << "role[acorns]" @knife.run - @node.run_list[0].should == "role[acorns]" - @node.run_list[1].should == "role[monkey]" - @node.run_list[2].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[acorns]") + expect(@node.run_list[1]).to eq("role[monkey]") + expect(@node.run_list[2]).to eq("role[duck]") end end @@ -104,9 +104,9 @@ describe Chef::Knife::NodeRunListAdd do @knife.name_args = [ "adam", "role[monkey], role[duck]" ] @node.run_list << "role[acorns]" @knife.run - @node.run_list[0].should == "role[acorns]" - @node.run_list[1].should == "role[monkey]" - @node.run_list[2].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[acorns]") + expect(@node.run_list[1]).to eq("role[monkey]") + expect(@node.run_list[2]).to eq("role[duck]") end end @@ -115,9 +115,9 @@ describe Chef::Knife::NodeRunListAdd do @knife.name_args = [ "adam", "role[monkey]", "role[duck]" ] @node.run_list << "role[acorns]" @knife.run - @node.run_list[0].should == "role[acorns]" - @node.run_list[1].should == "role[monkey]" - @node.run_list[2].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[acorns]") + expect(@node.run_list[1]).to eq("role[monkey]") + expect(@node.run_list[2]).to eq("role[duck]") end end @@ -126,9 +126,9 @@ describe Chef::Knife::NodeRunListAdd do @knife.name_args = [ "adam", "role[monkey]", "role[duck],recipe[bird::fly]" ] @node.run_list << "role[acorns]" @knife.run - @node.run_list[0].should == "role[acorns]" - @node.run_list[1].should == "role[monkey]" - @node.run_list[2].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[acorns]") + expect(@node.run_list[1]).to eq("role[monkey]") + expect(@node.run_list[2]).to eq("role[duck]") end end @@ -137,8 +137,8 @@ describe Chef::Knife::NodeRunListAdd do @knife.name_args = [ "adam", "role[monkey]," ] @node.run_list << "role[acorns]" @knife.run - @node.run_list[0].should == "role[acorns]" - @node.run_list[1].should == "role[monkey]" + expect(@node.run_list[0]).to eq("role[acorns]") + expect(@node.run_list[1]).to eq("role[monkey]") end end end diff --git a/spec/unit/knife/node_run_list_remove_spec.rb b/spec/unit/knife/node_run_list_remove_spec.rb index 5a008a3e07..ea951e21dd 100644 --- a/spec/unit/knife/node_run_list_remove_spec.rb +++ b/spec/unit/knife/node_run_list_remove_spec.rb @@ -27,33 +27,33 @@ describe Chef::Knife::NodeRunListRemove do @node = Chef::Node.new() @node.name("knifetest-node") @node.run_list << "role[monkey]" - @node.stub(:save).and_return(true) + allow(@node).to receive(:save).and_return(true) - @knife.ui.stub(:output).and_return(true) - @knife.ui.stub(:confirm).and_return(true) + allow(@knife.ui).to receive(:output).and_return(true) + allow(@knife.ui).to receive(:confirm).and_return(true) - Chef::Node.stub(:load).and_return(@node) + allow(Chef::Node).to receive(:load).and_return(@node) end describe "run" do it "should load the node" do - Chef::Node.should_receive(:load).with("adam").and_return(@node) + expect(Chef::Node).to receive(:load).with("adam").and_return(@node) @knife.run end it "should remove the item from the run list" do @knife.run - @node.run_list[0].should_not == 'role[monkey]' + expect(@node.run_list[0]).not_to eq('role[monkey]') end it "should save the node" do - @node.should_receive(:save).and_return(true) + expect(@node).to receive(:save).and_return(true) @knife.run end it "should print the run list" do @knife.config[:print_after] = true - @knife.ui.should_receive(:output).with({ "knifetest-node" => { 'run_list' => [] } }) + expect(@knife.ui).to receive(:output).with({ "knifetest-node" => { 'run_list' => [] } }) @knife.run end @@ -63,8 +63,8 @@ describe Chef::Knife::NodeRunListRemove do @node.run_list << 'recipe[duck::type]' @knife.name_args = [ 'adam', 'role[monkey],recipe[duck::type]' ] @knife.run - @node.run_list.should_not include('role[monkey]') - @node.run_list.should_not include('recipe[duck::type]') + expect(@node.run_list).not_to include('role[monkey]') + expect(@node.run_list).not_to include('recipe[duck::type]') end end end diff --git a/spec/unit/knife/node_run_list_set_spec.rb b/spec/unit/knife/node_run_list_set_spec.rb index 02281f8385..68daaafd70 100644 --- a/spec/unit/knife/node_run_list_set_spec.rb +++ b/spec/unit/knife/node_run_list_set_spec.rb @@ -24,30 +24,30 @@ describe Chef::Knife::NodeRunListSet do @knife = Chef::Knife::NodeRunListSet.new @knife.config = {} @knife.name_args = [ "adam", "role[monkey]" ] - @knife.stub(:output).and_return(true) + allow(@knife).to receive(:output).and_return(true) @node = Chef::Node.new() - @node.stub(:save).and_return(true) - Chef::Node.stub(:load).and_return(@node) + allow(@node).to receive(:save).and_return(true) + allow(Chef::Node).to receive(:load).and_return(@node) end describe "run" do it "should load the node" do - Chef::Node.should_receive(:load).with("adam") + expect(Chef::Node).to receive(:load).with("adam") @knife.run end it "should set the run list" do @knife.run - @node.run_list[0].should == 'role[monkey]' + expect(@node.run_list[0]).to eq('role[monkey]') end it "should save the node" do - @node.should_receive(:save) + expect(@node).to receive(:save) @knife.run end it "should print the run list" do - @knife.should_receive(:output).and_return(true) + expect(@knife).to receive(:output).and_return(true) @knife.run end @@ -55,8 +55,8 @@ describe Chef::Knife::NodeRunListSet do it "should set the run list to all the entries" do @knife.name_args = [ "adam", "role[monkey],role[duck]" ] @knife.run - @node.run_list[0].should == "role[monkey]" - @node.run_list[1].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[monkey]") + expect(@node.run_list[1]).to eq("role[duck]") end end @@ -64,8 +64,8 @@ describe Chef::Knife::NodeRunListSet do it "should set the run list to all the entries" do @knife.name_args = [ "adam", "role[monkey], role[duck]" ] @knife.run - @node.run_list[0].should == "role[monkey]" - @node.run_list[1].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[monkey]") + expect(@node.run_list[1]).to eq("role[duck]") end end @@ -73,8 +73,8 @@ describe Chef::Knife::NodeRunListSet do it "should set the run list to all the entries" do @knife.name_args = [ "adam", "role[monkey]", "role[duck]" ] @knife.run - @node.run_list[0].should == "role[monkey]" - @node.run_list[1].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[monkey]") + expect(@node.run_list[1]).to eq("role[duck]") end end @@ -82,8 +82,8 @@ describe Chef::Knife::NodeRunListSet do it "should add to the run list all the entries" do @knife.name_args = [ "adam", "role[monkey]", "role[duck],recipe[bird::fly]" ] @knife.run - @node.run_list[0].should == "role[monkey]" - @node.run_list[1].should == "role[duck]" + expect(@node.run_list[0]).to eq("role[monkey]") + expect(@node.run_list[1]).to eq("role[duck]") end end @@ -91,7 +91,7 @@ describe Chef::Knife::NodeRunListSet do it "should add to the run list one item" do @knife.name_args = [ "adam", "role[monkey]," ] @knife.run - @node.run_list[0].should == "role[monkey]" + expect(@node.run_list[0]).to eq("role[monkey]") end end @@ -99,15 +99,15 @@ describe Chef::Knife::NodeRunListSet do it "should overwrite any existing run list items" do @node.run_list << "role[acorns]" @node.run_list << "role[zebras]" - @node.run_list[0].should == "role[acorns]" - @node.run_list[1].should == "role[zebras]" - @node.run_list.run_list_items.size.should == 2 + expect(@node.run_list[0]).to eq("role[acorns]") + expect(@node.run_list[1]).to eq("role[zebras]") + expect(@node.run_list.run_list_items.size).to eq(2) @knife.name_args = [ "adam", "role[monkey]", "role[duck]" ] @knife.run - @node.run_list[0].should == "role[monkey]" - @node.run_list[1].should == "role[duck]" - @node.run_list.run_list_items.size.should == 2 + expect(@node.run_list[0]).to eq("role[monkey]") + expect(@node.run_list[1]).to eq("role[duck]") + expect(@node.run_list.run_list_items.size).to eq(2) end end @@ -117,13 +117,13 @@ describe Chef::Knife::NodeRunListSet do @stdout = StringIO.new @stderr = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end it "should exit" do @knife.name_args = [ "adam" ] - lambda { @knife.run }.should raise_error SystemExit + expect { @knife.run }.to raise_error SystemExit end it "should show the user" do @@ -131,8 +131,8 @@ describe Chef::Knife::NodeRunListSet do begin ; @knife.run ; rescue SystemExit ; end - @stdout.string.should eq "USAGE: knife node run_list set NODE ENTRIES (options)\n" - @stderr.string.should eq "FATAL: You must supply both a node name and a run list.\n" + expect(@stdout.string).to eq "USAGE: knife node run_list set NODE ENTRIES (options)\n" + expect(@stderr.string).to eq "FATAL: You must supply both a node name and a run list.\n" end end diff --git a/spec/unit/knife/role_bulk_delete_spec.rb b/spec/unit/knife/role_bulk_delete_spec.rb index eb1d3b4cff..5b79e52a04 100644 --- a/spec/unit/knife/role_bulk_delete_spec.rb +++ b/spec/unit/knife/role_bulk_delete_spec.rb @@ -27,53 +27,53 @@ describe Chef::Knife::RoleBulkDelete do } @knife.name_args = ["."] @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:confirm).and_return(true) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:confirm).and_return(true) @roles = Hash.new %w{dev staging production}.each do |role_name| role = Chef::Role.new() role.name(role_name) - role.stub(:destroy).and_return(true) + allow(role).to receive(:destroy).and_return(true) @roles[role_name] = role end - Chef::Role.stub(:list).and_return(@roles) + allow(Chef::Role).to receive(:list).and_return(@roles) end describe "run" do it "should get the list of the roles" do - Chef::Role.should_receive(:list).and_return(@roles) + expect(Chef::Role).to receive(:list).and_return(@roles) @knife.run end it "should print the roles you are about to delete" do @knife.run - @stdout.string.should match(/#{@knife.ui.list(@roles.keys.sort, :columns_down)}/) + expect(@stdout.string).to match(/#{@knife.ui.list(@roles.keys.sort, :columns_down)}/) end it "should confirm you really want to delete them" do - @knife.ui.should_receive(:confirm) + expect(@knife.ui).to receive(:confirm) @knife.run end it "should delete each role" do @roles.each_value do |r| - r.should_receive(:destroy) + expect(r).to receive(:destroy) end @knife.run end it "should only delete roles that match the regex" do @knife.name_args = ["dev"] - @roles["dev"].should_receive(:destroy) - @roles["staging"].should_not_receive(:destroy) - @roles["production"].should_not_receive(:destroy) + expect(@roles["dev"]).to receive(:destroy) + expect(@roles["staging"]).not_to receive(:destroy) + expect(@roles["production"]).not_to receive(:destroy) @knife.run end it "should exit if the regex is not provided" do @knife.name_args = [] - lambda { @knife.run }.should raise_error(SystemExit) + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/role_create_spec.rb b/spec/unit/knife/role_create_spec.rb index a4d7392b68..fb748c51f6 100644 --- a/spec/unit/knife/role_create_spec.rb +++ b/spec/unit/knife/role_create_spec.rb @@ -26,45 +26,45 @@ describe Chef::Knife::RoleCreate do :description => nil } @knife.name_args = [ "adam" ] - @knife.stub(:output).and_return(true) + allow(@knife).to receive(:output).and_return(true) @role = Chef::Role.new() - @role.stub(:save) - Chef::Role.stub(:new).and_return(@role) - @knife.stub(:edit_data).and_return(@role) + allow(@role).to receive(:save) + allow(Chef::Role).to receive(:new).and_return(@role) + allow(@knife).to receive(:edit_data).and_return(@role) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe "run" do it "should create a new role" do - Chef::Role.should_receive(:new).and_return(@role) + expect(Chef::Role).to receive(:new).and_return(@role) @knife.run end it "should set the role name" do - @role.should_receive(:name).with("adam") + expect(@role).to receive(:name).with("adam") @knife.run end it "should not print the role" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end it "should allow you to edit the data" do - @knife.should_receive(:edit_data).with(@role) + expect(@knife).to receive(:edit_data).with(@role) @knife.run end it "should save the role" do - @role.should_receive(:save) + expect(@role).to receive(:save) @knife.run end describe "with -d or --description" do it "should set the description" do @knife.config[:description] = "All is bob" - @role.should_receive(:description).with("All is bob") + expect(@role).to receive(:description).with("All is bob") @knife.run end end @@ -72,7 +72,7 @@ describe Chef::Knife::RoleCreate do describe "with -p or --print-after" do it "should pretty print the node, formatted for display" do @knife.config[:print_after] = true - @knife.should_receive(:output).with(@role) + expect(@knife).to receive(:output).with(@role) @knife.run end end diff --git a/spec/unit/knife/role_delete_spec.rb b/spec/unit/knife/role_delete_spec.rb index 0771446d49..b1a0d90410 100644 --- a/spec/unit/knife/role_delete_spec.rb +++ b/spec/unit/knife/role_delete_spec.rb @@ -26,40 +26,40 @@ describe Chef::Knife::RoleDelete do :print_after => nil } @knife.name_args = [ "adam" ] - @knife.stub(:output).and_return(true) - @knife.stub(:confirm).and_return(true) + allow(@knife).to receive(:output).and_return(true) + allow(@knife).to receive(:confirm).and_return(true) @role = Chef::Role.new() - @role.stub(:destroy).and_return(true) - Chef::Role.stub(:load).and_return(@role) + allow(@role).to receive(:destroy).and_return(true) + allow(Chef::Role).to receive(:load).and_return(@role) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe "run" do it "should confirm that you want to delete" do - @knife.should_receive(:confirm) + expect(@knife).to receive(:confirm) @knife.run end it "should load the Role" do - Chef::Role.should_receive(:load).with("adam").and_return(@role) + expect(Chef::Role).to receive(:load).with("adam").and_return(@role) @knife.run end it "should delete the Role" do - @role.should_receive(:destroy).and_return(@role) + expect(@role).to receive(:destroy).and_return(@role) @knife.run end it "should not print the Role" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end describe "with -p or --print-after" do it "should pretty print the Role, formatted for display" do @knife.config[:print_after] = true - @knife.should_receive(:output) + expect(@knife).to receive(:output) @knife.run end end diff --git a/spec/unit/knife/role_edit_spec.rb b/spec/unit/knife/role_edit_spec.rb index f6d3b41d98..0975c6458d 100644 --- a/spec/unit/knife/role_edit_spec.rb +++ b/spec/unit/knife/role_edit_spec.rb @@ -24,22 +24,22 @@ describe Chef::Knife::RoleEdit do @knife = Chef::Knife::RoleEdit.new @knife.config[:print_after] = nil @knife.name_args = [ "adam" ] - @knife.ui.stub(:output).and_return(true) + allow(@knife.ui).to receive(:output).and_return(true) @role = Chef::Role.new() - @role.stub(:save) - Chef::Role.stub(:load).and_return(@role) - @knife.ui.stub(:edit_data).and_return(@role) - @knife.ui.stub(:msg) + allow(@role).to receive(:save) + allow(Chef::Role).to receive(:load).and_return(@role) + allow(@knife.ui).to receive(:edit_data).and_return(@role) + allow(@knife.ui).to receive(:msg) end describe "run" do it "should load the role" do - Chef::Role.should_receive(:load).with("adam").and_return(@role) + expect(Chef::Role).to receive(:load).with("adam").and_return(@role) @knife.run end it "should edit the role data" do - @knife.ui.should_receive(:edit_data).with(@role) + expect(@knife.ui).to receive(:edit_data).with(@role) @knife.run end @@ -47,29 +47,29 @@ describe Chef::Knife::RoleEdit do pansy = Chef::Role.new @role.name("new_role_name") - @knife.ui.should_receive(:edit_data).with(@role).and_return(pansy) - pansy.should_receive(:save) + expect(@knife.ui).to receive(:edit_data).with(@role).and_return(pansy) + expect(pansy).to receive(:save) @knife.run end it "should not save the unedited role data" do pansy = Chef::Role.new - @knife.ui.should_receive(:edit_data).with(@role).and_return(pansy) - pansy.should_not_receive(:save) + expect(@knife.ui).to receive(:edit_data).with(@role).and_return(pansy) + expect(pansy).not_to receive(:save) @knife.run end it "should not print the role" do - @knife.ui.should_not_receive(:output) + expect(@knife.ui).not_to receive(:output) @knife.run end describe "with -p or --print-after" do it "should pretty print the role, formatted for display" do @knife.config[:print_after] = true - @knife.ui.should_receive(:output).with(@role) + expect(@knife.ui).to receive(:output).with(@role) @knife.run end end diff --git a/spec/unit/knife/role_from_file_spec.rb b/spec/unit/knife/role_from_file_spec.rb index 986414647c..9379f08de3 100644 --- a/spec/unit/knife/role_from_file_spec.rb +++ b/spec/unit/knife/role_from_file_spec.rb @@ -28,30 +28,30 @@ describe Chef::Knife::RoleFromFile do :print_after => nil } @knife.name_args = [ "adam.rb" ] - @knife.stub(:output).and_return(true) - @knife.stub(:confirm).and_return(true) + allow(@knife).to receive(:output).and_return(true) + allow(@knife).to receive(:confirm).and_return(true) @role = Chef::Role.new() - @role.stub(:save) - @knife.loader.stub(:load_from).and_return(@role) + allow(@role).to receive(:save) + allow(@knife.loader).to receive(:load_from).and_return(@role) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe "run" do it "should load from a file" do - @knife.loader.should_receive(:load_from).with('roles', 'adam.rb').and_return(@role) + expect(@knife.loader).to receive(:load_from).with('roles', 'adam.rb').and_return(@role) @knife.run end it "should not print the role" do - @knife.should_not_receive(:output) + expect(@knife).not_to receive(:output) @knife.run end describe "with -p or --print-after" do it "should print the role" do @knife.config[:print_after] = true - @knife.should_receive(:output) + expect(@knife).to receive(:output) @knife.run end end @@ -60,8 +60,8 @@ describe Chef::Knife::RoleFromFile do describe "run with multiple arguments" do it "should load each file" do @knife.name_args = [ "adam.rb", "caleb.rb" ] - @knife.loader.should_receive(:load_from).with('roles', 'adam.rb').and_return(@role) - @knife.loader.should_receive(:load_from).with('roles', 'caleb.rb').and_return(@role) + expect(@knife.loader).to receive(:load_from).with('roles', 'adam.rb').and_return(@role) + expect(@knife.loader).to receive(:load_from).with('roles', 'caleb.rb').and_return(@role) @knife.run end end diff --git a/spec/unit/knife/role_list_spec.rb b/spec/unit/knife/role_list_spec.rb index ef9642c04c..808a04d204 100644 --- a/spec/unit/knife/role_list_spec.rb +++ b/spec/unit/knife/role_list_spec.rb @@ -22,31 +22,31 @@ describe Chef::Knife::RoleList do before(:each) do Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::RoleList.new - @knife.stub(:output).and_return(true) + allow(@knife).to receive(:output).and_return(true) @list = { "foo" => "http://example.com/foo", "bar" => "http://example.com/foo" } - Chef::Role.stub(:list).and_return(@list) + allow(Chef::Role).to receive(:list).and_return(@list) end describe "run" do it "should list the roles" do - Chef::Role.should_receive(:list).and_return(@list) + expect(Chef::Role).to receive(:list).and_return(@list) @knife.run end it "should pretty print the list" do - Chef::Role.should_receive(:list).and_return(@list) - @knife.should_receive(:output).with([ "bar", "foo" ]) + expect(Chef::Role).to receive(:list).and_return(@list) + expect(@knife).to receive(:output).with([ "bar", "foo" ]) @knife.run end describe "with -w or --with-uri" do it "should pretty print the hash" do @knife.config[:with_uri] = true - Chef::Role.should_receive(:list).and_return(@list) - @knife.should_receive(:output).with(@list) + expect(Chef::Role).to receive(:list).and_return(@list) + expect(@knife).to receive(:output).with(@list) @knife.run end end diff --git a/spec/unit/knife/ssh_spec.rb b/spec/unit/knife/ssh_spec.rb index 10d63c9c74..501b02c933 100644 --- a/spec/unit/knife/ssh_spec.rb +++ b/spec/unit/knife/ssh_spec.rb @@ -45,8 +45,8 @@ describe Chef::Knife::Ssh do end def configure_query(node_array) - @query.stub(:search).and_return([node_array]) - Chef::Search::Query.stub(:new).and_return(@query) + allow(@query).to receive(:search).and_return([node_array]) + allow(Chef::Search::Query).to receive(:new).and_return(@query) end def self.should_return_specified_attributes @@ -54,7 +54,7 @@ describe Chef::Knife::Ssh do @knife.config[:attribute] = "ipaddress" @knife.config[:attribute_from_cli] = "ipaddress" configure_query([@node_foo, @node_bar]) - @knife.should_receive(:session_from_list).with([['10.0.0.1', nil], ['10.0.0.2', nil]]) + expect(@knife).to receive(:session_from_list).with([['10.0.0.1', nil], ['10.0.0.2', nil]]) @knife.configure_session end @@ -62,14 +62,14 @@ describe Chef::Knife::Ssh do @knife.config[:attribute] = "config_file" # this value will be the config file @knife.config[:attribute_from_cli] = "ipaddress" # this is the value of the command line via #configure_attribute configure_query([@node_foo, @node_bar]) - @knife.should_receive(:session_from_list).with([['10.0.0.1', nil], ['10.0.0.2', nil]]) + expect(@knife).to receive(:session_from_list).with([['10.0.0.1', nil], ['10.0.0.2', nil]]) @knife.configure_session end end it "searchs for and returns an array of fqdns" do configure_query([@node_foo, @node_bar]) - @knife.should_receive(:session_from_list).with([ + expect(@knife).to receive(:session_from_list).with([ ['foo.example.org', nil], ['bar.example.org', nil] ]) @@ -86,7 +86,7 @@ describe Chef::Knife::Ssh do it "returns an array of cloud public hostnames" do configure_query([@node_foo, @node_bar]) - @knife.should_receive(:session_from_list).with([ + expect(@knife).to receive(:session_from_list).with([ ['ec2-10-0-0-1.compute-1.amazonaws.com', nil], ['ec2-10-0-0-2.compute-1.amazonaws.com', nil] ]) @@ -98,22 +98,22 @@ describe Chef::Knife::Ssh do it "should raise an error if no host are found" do configure_query([ ]) - @knife.ui.should_receive(:fatal) - @knife.should_receive(:exit).with(10) + expect(@knife.ui).to receive(:fatal) + expect(@knife).to receive(:exit).with(10) @knife.configure_session end context "when there are some hosts found but they do not have an attribute to connect with" do before do - @query.stub(:search).and_return([[@node_foo, @node_bar]]) + allow(@query).to receive(:search).and_return([[@node_foo, @node_bar]]) @node_foo.automatic_attrs[:fqdn] = nil @node_bar.automatic_attrs[:fqdn] = nil - Chef::Search::Query.stub(:new).and_return(@query) + allow(Chef::Search::Query).to receive(:new).and_return(@query) end it "should raise a specific error (CHEF-3402)" do - @knife.ui.should_receive(:fatal).with(/^2 nodes found/) - @knife.should_receive(:exit).with(10) + expect(@knife.ui).to receive(:fatal).with(/^2 nodes found/) + expect(@knife).to receive(:exit).with(10) @knife.configure_session end end @@ -126,7 +126,7 @@ describe Chef::Knife::Ssh do it "returns an array of provided values" do @knife.instance_variable_set(:@name_args, ["foo.example.org bar.example.org"]) - @knife.should_receive(:session_from_list).with(['foo.example.org', 'bar.example.org']) + expect(@knife).to receive(:session_from_list).with(['foo.example.org', 'bar.example.org']) @knife.configure_session end end @@ -140,34 +140,34 @@ describe Chef::Knife::Ssh do it "should return fqdn by default" do @knife.configure_attribute - @knife.config[:attribute].should == "fqdn" + expect(@knife.config[:attribute]).to eq("fqdn") end it "should return the value set in the configuration file" do Chef::Config[:knife][:ssh_attribute] = "config_file" @knife.configure_attribute - @knife.config[:attribute].should == "config_file" + expect(@knife.config[:attribute]).to eq("config_file") end it "should return the value set on the command line" do @knife.config[:attribute] = "command_line" @knife.configure_attribute - @knife.config[:attribute].should == "command_line" + expect(@knife.config[:attribute]).to eq("command_line") end it "should set attribute_from_cli to the value of attribute from the command line" do @knife.config[:attribute] = "command_line" @knife.configure_attribute - @knife.config[:attribute].should == "command_line" - @knife.config[:attribute_from_cli].should == "command_line" + expect(@knife.config[:attribute]).to eq("command_line") + expect(@knife.config[:attribute_from_cli]).to eq("command_line") end it "should prefer the command line over the config file for the value of attribute_from_cli" do Chef::Config[:knife][:ssh_attribute] = "config_file" @knife.config[:attribute] = "command_line" @knife.configure_attribute - @knife.config[:attribute].should == "command_line" - @knife.config[:attribute_from_cli].should == "command_line" + expect(@knife.config[:attribute]).to eq("command_line") + expect(@knife.config[:attribute_from_cli]).to eq("command_line") end end @@ -175,22 +175,22 @@ describe Chef::Knife::Ssh do before :each do @knife.instance_variable_set(:@longest, 0) ssh_config = {:timeout => 50, :user => "locutus", :port => 23 } - Net::SSH.stub(:configuration_for).with('the.b.org').and_return(ssh_config) + allow(Net::SSH).to receive(:configuration_for).with('the.b.org').and_return(ssh_config) end it "uses the port from an ssh config file" do @knife.session_from_list([['the.b.org', nil]]) - @knife.session.servers[0].port.should == 23 + expect(@knife.session.servers[0].port).to eq(23) end it "uses the port from a cloud attr" do @knife.session_from_list([['the.b.org', 123]]) - @knife.session.servers[0].port.should == 123 + expect(@knife.session.servers[0].port).to eq(123) end it "uses the user from an ssh config file" do @knife.session_from_list([['the.b.org', 123]]) - @knife.session.servers[0].user.should == "locutus" + expect(@knife.session.servers[0].user).to eq("locutus") end end @@ -206,26 +206,26 @@ describe Chef::Knife::Ssh do let(:command) { "false" } before do - execution_channel. - should_receive(:on_request). + expect(execution_channel). + to receive(:on_request). and_yield(nil, double(:data_stream, :read_long => exit_status)) - session_channel. - should_receive(:exec). + expect(session_channel). + to receive(:exec). with(command). and_yield(execution_channel, true) - execution_channel2. - should_receive(:on_request). + expect(execution_channel2). + to receive(:on_request). and_yield(nil, double(:data_stream, :read_long => exit_status2)) - session_channel2. - should_receive(:exec). + expect(session_channel2). + to receive(:exec). with(command). and_yield(execution_channel2, true) - session. - should_receive(:open_channel). + expect(session). + to receive(:open_channel). and_yield(session_channel). and_yield(session_channel2) end @@ -235,7 +235,7 @@ describe Chef::Knife::Ssh do let(:exit_status2) { 0 } it "returns a 0 exit code" do - @knife.ssh_command(command, session).should == 0 + expect(@knife.ssh_command(command, session)).to eq(0) end end @@ -244,7 +244,7 @@ describe Chef::Knife::Ssh do let(:exit_status2) { 0 } it "returns a non-zero exit code" do - @knife.ssh_command(command, session).should == 1 + expect(@knife.ssh_command(command, session)).to eq(1) end end @@ -253,7 +253,7 @@ describe Chef::Knife::Ssh do let(:exit_status2) { 2 } it "returns a non-zero exit code" do - @knife.ssh_command(command, session).should == 2 + expect(@knife.ssh_command(command, session)).to eq(2) end end end @@ -261,9 +261,9 @@ describe Chef::Knife::Ssh do describe "#run" do before do @query = Chef::Search::Query.new - @query.should_receive(:search).and_return([[@node_foo]]) - Chef::Search::Query.stub(:new).and_return(@query) - @knife.stub(:ssh_command).and_return(exit_code) + expect(@query).to receive(:search).and_return([[@node_foo]]) + allow(Chef::Search::Query).to receive(:new).and_return(@query) + allow(@knife).to receive(:ssh_command).and_return(exit_code) @knife.name_args = ['*:*', 'false'] end @@ -271,7 +271,7 @@ describe Chef::Knife::Ssh do let(:exit_code) { 1 } it "should exit with a non-zero exit code" do - @knife.should_receive(:exit).with(exit_code) + expect(@knife).to receive(:exit).with(exit_code) @knife.run end end @@ -280,7 +280,7 @@ describe Chef::Knife::Ssh do let(:exit_code) { 0 } it "should not exit" do - @knife.should_not_receive(:exit) + expect(@knife).not_to receive(:exit) @knife.run end end @@ -296,23 +296,23 @@ describe Chef::Knife::Ssh do # in this case ssh_password_ng exists, but ssh_password does not it "should prompt for a password when ssh_passsword_ng is nil" do @knife.config[:ssh_password_ng] = nil - @knife.should_receive(:get_password).and_return("mysekretpassw0rd") + expect(@knife).to receive(:get_password).and_return("mysekretpassw0rd") @knife.configure_password - @knife.config[:ssh_password].should == "mysekretpassw0rd" + expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end it "should set ssh_password to false if ssh_password_ng is false" do @knife.config[:ssh_password_ng] = false - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should be_false + expect(@knife.config[:ssh_password]).to be_falsey end it "should set ssh_password to ssh_password_ng if we set a password" do @knife.config[:ssh_password_ng] = "mysekretpassw0rd" - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should == "mysekretpassw0rd" + expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end end @@ -320,23 +320,23 @@ describe Chef::Knife::Ssh do # in this case ssh_password exists, but ssh_password_ng does not it "should set ssh_password to nil when ssh_password is nil" do @knife.config[:ssh_password] = nil - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should be_nil + expect(@knife.config[:ssh_password]).to be_nil end it "should set ssh_password to false when ssh_password is false" do @knife.config[:ssh_password] = false - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should be_false + expect(@knife.config[:ssh_password]).to be_falsey end it "should set ssh_password to ssh_password if we set a password" do @knife.config[:ssh_password] = "mysekretpassw0rd" - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should == "mysekretpassw0rd" + expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end end context "when setting ssh_password in the config variable" do @@ -347,23 +347,23 @@ describe Chef::Knife::Ssh do # in this case ssh_password_ng exists, but ssh_password does not it "should prompt for a password when ssh_passsword_ng is nil" do @knife.config[:ssh_password_ng] = nil - @knife.should_receive(:get_password).and_return("mysekretpassw0rd") + expect(@knife).to receive(:get_password).and_return("mysekretpassw0rd") @knife.configure_password - @knife.config[:ssh_password].should == "mysekretpassw0rd" + expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end it "should set ssh_password to the configured knife.rb value if ssh_password_ng is false" do @knife.config[:ssh_password_ng] = false - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should == "my_knife_passw0rd" + expect(@knife.config[:ssh_password]).to eq("my_knife_passw0rd") end it "should set ssh_password to ssh_password_ng if we set a password" do @knife.config[:ssh_password_ng] = "mysekretpassw0rd" - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should == "mysekretpassw0rd" + expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end end @@ -371,23 +371,23 @@ describe Chef::Knife::Ssh do # in this case ssh_password exists, but ssh_password_ng does not it "should set ssh_password to the configured knife.rb value when ssh_password is nil" do @knife.config[:ssh_password] = nil - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should == "my_knife_passw0rd" + expect(@knife.config[:ssh_password]).to eq("my_knife_passw0rd") end it "should set ssh_password to the configured knife.rb value when ssh_password is false" do @knife.config[:ssh_password] = false - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should == "my_knife_passw0rd" + expect(@knife.config[:ssh_password]).to eq("my_knife_passw0rd") end it "should set ssh_password to ssh_password if we set a password" do @knife.config[:ssh_password] = "mysekretpassw0rd" - @knife.should_not_receive(:get_password) + expect(@knife).not_to receive(:get_password) @knife.configure_password - @knife.config[:ssh_password].should == "mysekretpassw0rd" + expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd") end end end diff --git a/spec/unit/knife/ssl_check_spec.rb b/spec/unit/knife/ssl_check_spec.rb index bb803ce2ca..8eda555108 100644 --- a/spec/unit/knife/ssl_check_spec.rb +++ b/spec/unit/knife/ssl_check_spec.rb @@ -35,8 +35,8 @@ describe Chef::Knife::SslCheck do subject(:ssl_check) do s = Chef::Knife::SslCheck.new - s.ui.stub(:stdout).and_return(stdout_io) - s.ui.stub(:stderr).and_return(stderr_io) + allow(s.ui).to receive(:stdout).and_return(stdout_io) + allow(s.ui).to receive(:stderr).and_return(stderr_io) s.name_args = name_args s end @@ -106,17 +106,17 @@ E before do Chef::Config[:trusted_certs_dir] = trusted_certs_dir - ssl_check.stub(:trusted_certificates).and_return([trusted_cert_file]) - store.stub(:add_cert).with(certificate) - OpenSSL::X509::Store.stub(:new).and_return(store) - OpenSSL::X509::Certificate.stub(:new).with(IO.read(trusted_cert_file)).and_return(certificate) - ssl_check.stub(:verify_cert).and_return(true) - ssl_check.stub(:verify_cert_host).and_return(true) + allow(ssl_check).to receive(:trusted_certificates).and_return([trusted_cert_file]) + allow(store).to receive(:add_cert).with(certificate) + allow(OpenSSL::X509::Store).to receive(:new).and_return(store) + allow(OpenSSL::X509::Certificate).to receive(:new).with(IO.read(trusted_cert_file)).and_return(certificate) + allow(ssl_check).to receive(:verify_cert).and_return(true) + allow(ssl_check).to receive(:verify_cert_host).and_return(true) end context "when the trusted certificates have valid X509 properties" do before do - store.stub(:verify).with(certificate).and_return(true) + allow(store).to receive(:verify).with(certificate).and_return(true) end it "does not generate any X509 warnings" do @@ -127,8 +127,8 @@ E context "when the trusted certificates have invalid X509 properties" do before do - store.stub(:verify).with(certificate).and_return(false) - store.stub(:error_string).and_return("unable to get local issuer certificate") + allow(store).to receive(:verify).with(certificate).and_return(false) + allow(store).to receive(:error_string).and_return("unable to get local issuer certificate") end it "generates a warning message with invalid certificate file names" do @@ -145,8 +145,8 @@ E let(:ssl_socket) { double(OpenSSL::SSL::SSLSocket) } before do - TCPSocket.should_receive(:new).with("foo.example.com", 8443).and_return(tcp_socket) - OpenSSL::SSL::SSLSocket.should_receive(:new).with(tcp_socket, ssl_check.verify_peer_ssl_context).and_return(ssl_socket) + expect(TCPSocket).to receive(:new).with("foo.example.com", 8443).and_return(tcp_socket) + expect(OpenSSL::SSL::SSLSocket).to receive(:new).with(tcp_socket, ssl_check.verify_peer_ssl_context).and_return(ssl_socket) end def run @@ -160,9 +160,9 @@ E context "when the remote host's certificate is valid" do before do - ssl_check.should_receive(:verify_X509).and_return(true) # X509 valid certs (no warn) - ssl_socket.should_receive(:connect) # no error - ssl_socket.should_receive(:post_connection_check).with("foo.example.com") # no error + expect(ssl_check).to receive(:verify_X509).and_return(true) # X509 valid certs (no warn) + expect(ssl_socket).to receive(:connect) # no error + expect(ssl_socket).to receive(:post_connection_check).with("foo.example.com") # no error end it "prints a success message" do @@ -182,23 +182,23 @@ E before do trap(:INT, "DEFAULT") - TCPSocket.should_receive(:new). + expect(TCPSocket).to receive(:new). with("foo.example.com", 8443). and_return(tcp_socket_for_debug) - OpenSSL::SSL::SSLSocket.should_receive(:new). + expect(OpenSSL::SSL::SSLSocket).to receive(:new). with(tcp_socket_for_debug, ssl_check.noverify_peer_ssl_context). and_return(ssl_socket_for_debug) end context "when the certificate's CN does not match the hostname" do before do - ssl_check.should_receive(:verify_X509).and_return(true) # X509 valid certs - ssl_socket.should_receive(:connect) # no error - ssl_socket.should_receive(:post_connection_check). + expect(ssl_check).to receive(:verify_X509).and_return(true) # X509 valid certs + expect(ssl_socket).to receive(:connect) # no error + expect(ssl_socket).to receive(:post_connection_check). with("foo.example.com"). and_raise(OpenSSL::SSL::SSLError) - ssl_socket_for_debug.should_receive(:connect) - ssl_socket_for_debug.should_receive(:peer_cert).and_return(self_signed_crt) + expect(ssl_socket_for_debug).to receive(:connect) + expect(ssl_socket_for_debug).to receive(:peer_cert).and_return(self_signed_crt) end it "shows the CN used by the certificate and prints an error" do @@ -212,11 +212,11 @@ E context "when the cert is not signed by any trusted authority" do before do - ssl_check.should_receive(:verify_X509).and_return(true) # X509 valid certs - ssl_socket.should_receive(:connect). + expect(ssl_check).to receive(:verify_X509).and_return(true) # X509 valid certs + expect(ssl_socket).to receive(:connect). and_raise(OpenSSL::SSL::SSLError) - ssl_socket_for_debug.should_receive(:connect) - ssl_socket_for_debug.should_receive(:peer_cert).and_return(self_signed_crt) + expect(ssl_socket_for_debug).to receive(:connect) + expect(ssl_socket_for_debug).to receive(:peer_cert).and_return(self_signed_crt) end it "shows the CN used by the certificate and prints an error" do diff --git a/spec/unit/knife/ssl_fetch_spec.rb b/spec/unit/knife/ssl_fetch_spec.rb index 0d3c8913f7..24101dbe7a 100644 --- a/spec/unit/knife/ssl_fetch_spec.rb +++ b/spec/unit/knife/ssl_fetch_spec.rb @@ -36,8 +36,8 @@ describe Chef::Knife::SslFetch do subject(:ssl_fetch) do s = Chef::Knife::SslFetch.new s.name_args = name_args - s.ui.stub(:stdout).and_return(stdout_io) - s.ui.stub(:stderr).and_return(stderr_io) + allow(s.ui).to receive(:stdout).and_return(stdout_io) + allow(s.ui).to receive(:stderr).and_return(stderr_io) s end @@ -131,10 +131,10 @@ E before do Chef::Config.trusted_certs_dir = trusted_certs_dir - TCPSocket.should_receive(:new).with("foo.example.com", 8443).and_return(tcp_socket) - OpenSSL::SSL::SSLSocket.should_receive(:new).with(tcp_socket, ssl_fetch.noverify_peer_ssl_context).and_return(ssl_socket) - ssl_socket.should_receive(:connect) - ssl_socket.should_receive(:peer_cert_chain).and_return([self_signed_crt]) + expect(TCPSocket).to receive(:new).with("foo.example.com", 8443).and_return(tcp_socket) + expect(OpenSSL::SSL::SSLSocket).to receive(:new).with(tcp_socket, ssl_fetch.noverify_peer_ssl_context).and_return(ssl_socket) + expect(ssl_socket).to receive(:connect) + expect(ssl_socket).to receive(:peer_cert_chain).and_return([self_signed_crt]) end after do diff --git a/spec/unit/knife/status_spec.rb b/spec/unit/knife/status_spec.rb index bb43dd25e5..2522bc61b1 100644 --- a/spec/unit/knife/status_spec.rb +++ b/spec/unit/knife/status_spec.rb @@ -25,18 +25,18 @@ describe Chef::Knife::Status do n.automatic_attrs["ohai_time"] = 1343845969 end query = double("Chef::Search::Query") - query.stub(:search).and_yield(node) - Chef::Search::Query.stub(:new).and_return(query) + allow(query).to receive(:search).and_yield(node) + allow(Chef::Search::Query).to receive(:new).and_return(query) @knife = Chef::Knife::Status.new @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end describe "run" do it "should not colorize output unless it's writing to a tty" do @knife.run - @stdout.string.match(/foobar/).should_not be_nil - @stdout.string.match(/\e.*ago/).should be_nil + expect(@stdout.string.match(/foobar/)).not_to be_nil + expect(@stdout.string.match(/\e.*ago/)).to be_nil end end end diff --git a/spec/unit/knife/tag_create_spec.rb b/spec/unit/knife/tag_create_spec.rb index bafea8d268..586ec118bd 100644 --- a/spec/unit/knife/tag_create_spec.rb +++ b/spec/unit/knife/tag_create_spec.rb @@ -7,17 +7,17 @@ describe Chef::Knife::TagCreate do @knife.name_args = [ Chef::Config[:node_name], "happytag" ] @node = Chef::Node.new - @node.stub :save - Chef::Node.stub(:load).and_return @node + allow(@node).to receive :save + allow(Chef::Node).to receive(:load).and_return @node @stderr = StringIO.new - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end describe "run" do it "can create tags on a node" do @knife.run - @node.tags.should == ["happytag"] - @stderr.string.should match /created tags happytag.+node webmonkey.example.com/i + expect(@node.tags).to eq(["happytag"]) + expect(@stderr.string).to match /created tags happytag.+node webmonkey.example.com/i end end end diff --git a/spec/unit/knife/tag_delete_spec.rb b/spec/unit/knife/tag_delete_spec.rb index 514228f0a2..e7fa108947 100644 --- a/spec/unit/knife/tag_delete_spec.rb +++ b/spec/unit/knife/tag_delete_spec.rb @@ -7,19 +7,19 @@ describe Chef::Knife::TagDelete do @knife.name_args = [ Chef::Config[:node_name], "sadtag" ] @node = Chef::Node.new - @node.stub :save + allow(@node).to receive :save @node.tags << "sadtag" << "happytag" - Chef::Node.stub(:load).and_return @node + allow(Chef::Node).to receive(:load).and_return @node @stderr = StringIO.new - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) end describe "run" do it "can delete tags on a node" do - @node.tags.should == ["sadtag", "happytag"] + expect(@node.tags).to eq(["sadtag", "happytag"]) @knife.run - @node.tags.should == ["happytag"] - @stderr.string.should match /deleted.+sadtag/i + expect(@node.tags).to eq(["happytag"]) + expect(@stderr.string).to match /deleted.+sadtag/i end end end diff --git a/spec/unit/knife/tag_list_spec.rb b/spec/unit/knife/tag_list_spec.rb index 3724a5c0b7..9c71d22f06 100644 --- a/spec/unit/knife/tag_list_spec.rb +++ b/spec/unit/knife/tag_list_spec.rb @@ -7,16 +7,16 @@ describe Chef::Knife::TagList do @knife.name_args = [ Chef::Config[:node_name], "sadtag" ] @node = Chef::Node.new - @node.stub :save + allow(@node).to receive :save @node.tags << "sadtag" << "happytag" - Chef::Node.stub(:load).and_return @node + allow(Chef::Node).to receive(:load).and_return @node end describe "run" do it "can list tags on a node" do expected = %w(sadtag happytag) - @node.tags.should == expected - @knife.should_receive(:output).with(expected) + expect(@node.tags).to eq(expected) + expect(@knife).to receive(:output).with(expected) @knife.run end end diff --git a/spec/unit/knife/user_create_spec.rb b/spec/unit/knife/user_create_spec.rb index 58ef868053..ad8821cd0e 100644 --- a/spec/unit/knife/user_create_spec.rb +++ b/spec/unit/knife/user_create_spec.rb @@ -26,8 +26,8 @@ describe Chef::Knife::UserCreate do @stdout = StringIO.new @stderr = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) - @knife.ui.stub(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) @knife.name_args = [ 'a_user' ] @knife.config[:user_password] = "foobar" @@ -36,53 +36,53 @@ describe Chef::Knife::UserCreate do @user_with_private_key = Chef::User.new @user_with_private_key.name "a_user" @user_with_private_key.private_key 'private_key' - @user.stub(:create).and_return(@user_with_private_key) - Chef::User.stub(:new).and_return(@user) - Chef::User.stub(:from_hash).and_return(@user) - @knife.stub(:edit_data).and_return(@user.to_hash) + allow(@user).to receive(:create).and_return(@user_with_private_key) + allow(Chef::User).to receive(:new).and_return(@user) + allow(Chef::User).to receive(:from_hash).and_return(@user) + allow(@knife).to receive(:edit_data).and_return(@user.to_hash) end it "creates a new user" do - Chef::User.should_receive(:new).and_return(@user) - @user.should_receive(:create) + expect(Chef::User).to receive(:new).and_return(@user) + expect(@user).to receive(:create) @knife.run - @stderr.string.should match /created user.+a_user/i + expect(@stderr.string).to match /created user.+a_user/i end it "sets the password" do @knife.config[:user_password] = "a_password" - @user.should_receive(:password).with("a_password") + expect(@user).to receive(:password).with("a_password") @knife.run end it "exits with an error if password is blank" do @knife.config[:user_password] = '' - lambda { @knife.run }.should raise_error SystemExit - @stderr.string.should match /You must specify a non-blank password/ + expect { @knife.run }.to raise_error SystemExit + expect(@stderr.string).to match /You must specify a non-blank password/ end it "sets the user name" do - @user.should_receive(:name).with("a_user") + expect(@user).to receive(:name).with("a_user") @knife.run end it "sets the public key if given" do @knife.config[:user_key] = "/a/filename" - File.stub(:read).with(File.expand_path("/a/filename")).and_return("a_key") - @user.should_receive(:public_key).with("a_key") + allow(File).to receive(:read).with(File.expand_path("/a/filename")).and_return("a_key") + expect(@user).to receive(:public_key).with("a_key") @knife.run end it "allows you to edit the data" do - @knife.should_receive(:edit_data).with(@user) + expect(@knife).to receive(:edit_data).with(@user) @knife.run end it "writes the private key to a file when --file is specified" do @knife.config[:file] = "/tmp/a_file" filehandle = double("filehandle") - filehandle.should_receive(:print).with('private_key') - File.should_receive(:open).with("/tmp/a_file", "w").and_yield(filehandle) + expect(filehandle).to receive(:print).with('private_key') + expect(File).to receive(:open).with("/tmp/a_file", "w").and_yield(filehandle) @knife.run end end diff --git a/spec/unit/knife/user_delete_spec.rb b/spec/unit/knife/user_delete_spec.rb index be027e5128..94cfbf3db1 100644 --- a/spec/unit/knife/user_delete_spec.rb +++ b/spec/unit/knife/user_delete_spec.rb @@ -26,14 +26,14 @@ describe Chef::Knife::UserDelete do end it 'deletes the user' do - @knife.should_receive(:delete_object).with(Chef::User, 'my_user') + expect(@knife).to receive(:delete_object).with(Chef::User, 'my_user') @knife.run end it 'prints usage and exits when a user name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/user_edit_spec.rb b/spec/unit/knife/user_edit_spec.rb index 20a4c0d9e9..0eb75cfa9b 100644 --- a/spec/unit/knife/user_edit_spec.rb +++ b/spec/unit/knife/user_edit_spec.rb @@ -25,23 +25,23 @@ describe Chef::Knife::UserEdit do Chef::Knife::UserEdit.load_deps @knife = Chef::Knife::UserEdit.new - @knife.ui.stub(:stderr).and_return(@stderr) - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stderr).and_return(@stderr) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) @knife.name_args = [ 'my_user' ] @knife.config[:disable_editing] = true end it 'loads and edits the user' do data = { :name => "my_user" } - Chef::User.stub(:load).with("my_user").and_return(data) - @knife.should_receive(:edit_data).with(data).and_return(data) + allow(Chef::User).to receive(:load).with("my_user").and_return(data) + expect(@knife).to receive(:edit_data).with(data).and_return(data) @knife.run end it 'prints usage and exits when a user name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife/user_list_spec.rb b/spec/unit/knife/user_list_spec.rb index 7a47f9ddba..db097a5c16 100644 --- a/spec/unit/knife/user_list_spec.rb +++ b/spec/unit/knife/user_list_spec.rb @@ -25,8 +25,8 @@ describe Chef::Knife::UserList do end it 'lists the users' do - Chef::User.should_receive(:list) - @knife.should_receive(:format_list_for_display) + expect(Chef::User).to receive(:list) + expect(@knife).to receive(:format_list_for_display) @knife.run end end diff --git a/spec/unit/knife/user_reregister_spec.rb b/spec/unit/knife/user_reregister_spec.rb index 1cbbdb47d2..1268716f40 100644 --- a/spec/unit/knife/user_reregister_spec.rb +++ b/spec/unit/knife/user_reregister_spec.rb @@ -24,30 +24,30 @@ describe Chef::Knife::UserReregister do @knife = Chef::Knife::UserReregister.new @knife.name_args = [ 'a_user' ] @user_mock = double('user_mock', :private_key => "private_key") - Chef::User.stub(:load).and_return(@user_mock) + allow(Chef::User).to receive(:load).and_return(@user_mock) @stdout = StringIO.new - @knife.ui.stub(:stdout).and_return(@stdout) + allow(@knife.ui).to receive(:stdout).and_return(@stdout) end it 'prints usage and exits when a user name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end it 'reregisters the user and prints the key' do - @user_mock.should_receive(:reregister).and_return(@user_mock) + expect(@user_mock).to receive(:reregister).and_return(@user_mock) @knife.run - @stdout.string.should match( /private_key/ ) + expect(@stdout.string).to match( /private_key/ ) end it 'writes the private key to a file when --file is specified' do - @user_mock.should_receive(:reregister).and_return(@user_mock) + expect(@user_mock).to receive(:reregister).and_return(@user_mock) @knife.config[:file] = '/tmp/a_file' filehandle = StringIO.new - File.should_receive(:open).with('/tmp/a_file', 'w').and_yield(filehandle) + expect(File).to receive(:open).with('/tmp/a_file', 'w').and_yield(filehandle) @knife.run - filehandle.string.should == "private_key" + expect(filehandle.string).to eq("private_key") end end diff --git a/spec/unit/knife/user_show_spec.rb b/spec/unit/knife/user_show_spec.rb index af8485ad7d..f97cbc3f13 100644 --- a/spec/unit/knife/user_show_spec.rb +++ b/spec/unit/knife/user_show_spec.rb @@ -27,15 +27,15 @@ describe Chef::Knife::UserShow do end it 'loads and displays the user' do - Chef::User.should_receive(:load).with('my_user').and_return(@user_mock) - @knife.should_receive(:format_for_display).with(@user_mock) + expect(Chef::User).to receive(:load).with('my_user').and_return(@user_mock) + expect(@knife).to receive(:format_for_display).with(@user_mock) @knife.run end it 'prints usage and exits when a user name is not provided' do @knife.name_args = [] - @knife.should_receive(:show_usage) - @knife.ui.should_receive(:fatal) - lambda { @knife.run }.should raise_error(SystemExit) + expect(@knife).to receive(:show_usage) + expect(@knife.ui).to receive(:fatal) + expect { @knife.run }.to raise_error(SystemExit) end end diff --git a/spec/unit/knife_spec.rb b/spec/unit/knife_spec.rb index 6d4763e087..d35ba4fa5f 100644 --- a/spec/unit/knife_spec.rb +++ b/spec/unit/knife_spec.rb @@ -31,16 +31,16 @@ describe Chef::Knife do Chef::Config[:node_name] = "webmonkey.example.com" # Prevent gratuitous code reloading: - Chef::Knife.stub(:load_commands) + allow(Chef::Knife).to receive(:load_commands) @knife = Chef::Knife.new - @knife.ui.stub(:puts) - @knife.ui.stub(:print) - Chef::Log.stub(:init) - Chef::Log.stub(:level) + allow(@knife.ui).to receive(:puts) + allow(@knife.ui).to receive(:print) + allow(Chef::Log).to receive(:init) + allow(Chef::Log).to receive(:level) [:debug, :info, :warn, :error, :crit].each do |level_sym| - Chef::Log.stub(level_sym) + allow(Chef::Log).to receive(level_sym) end - Chef::Knife.stub(:puts) + allow(Chef::Knife).to receive(:puts) @stderr = StringIO.new end @@ -61,27 +61,27 @@ describe Chef::Knife do end it "has a category based on its name" do - KnifeSpecs::TestNameMapping.subcommand_category.should == 'test' + expect(KnifeSpecs::TestNameMapping.subcommand_category).to eq('test') end it "has an explictly defined category if set" do - KnifeSpecs::TestExplicitCategory.subcommand_category.should == 'cookbook site' + expect(KnifeSpecs::TestExplicitCategory.subcommand_category).to eq('cookbook site') end it "can reference the subcommand by its snake cased name" do - Chef::Knife.subcommands['test_name_mapping'].should equal(KnifeSpecs::TestNameMapping) + expect(Chef::Knife.subcommands['test_name_mapping']).to equal(KnifeSpecs::TestNameMapping) end it "lists subcommands by category" do - Chef::Knife.subcommands_by_category['test'].should include('test_name_mapping') + expect(Chef::Knife.subcommands_by_category['test']).to include('test_name_mapping') end it "lists subcommands by category when the subcommands have explicit categories" do - Chef::Knife.subcommands_by_category['cookbook site'].should include('test_explicit_category') + expect(Chef::Knife.subcommands_by_category['cookbook site']).to include('test_explicit_category') end it "has empty dependency_loader list by default" do - KnifeSpecs::TestNameMapping.dependency_loaders.should be_empty + expect(KnifeSpecs::TestNameMapping.dependency_loaders).to be_empty end end @@ -97,22 +97,22 @@ describe Chef::Knife do Chef::Knife.load_commands - Chef::Knife.subcommands.should have_key("super_awesome_command") - Chef::Knife.subcommands["super_awesome_command"].should == SuperAwesomeCommand + expect(Chef::Knife.subcommands).to have_key("super_awesome_command") + expect(Chef::Knife.subcommands["super_awesome_command"]).to eq(SuperAwesomeCommand) end it "guesses a category from a given ARGV" do Chef::Knife.subcommands_by_category["cookbook"] << :cookbook Chef::Knife.subcommands_by_category["cookbook site"] << :cookbook_site - Chef::Knife.guess_category(%w{cookbook foo bar baz}).should == 'cookbook' - Chef::Knife.guess_category(%w{cookbook site foo bar baz}).should == 'cookbook site' - Chef::Knife.guess_category(%w{cookbook site --help}).should == 'cookbook site' + expect(Chef::Knife.guess_category(%w{cookbook foo bar baz})).to eq('cookbook') + expect(Chef::Knife.guess_category(%w{cookbook site foo bar baz})).to eq('cookbook site') + expect(Chef::Knife.guess_category(%w{cookbook site --help})).to eq('cookbook site') end it "finds a subcommand class based on ARGV" do Chef::Knife.subcommands["cookbook_site_vendor"] = :CookbookSiteVendor Chef::Knife.subcommands["cookbook"] = :Cookbook - Chef::Knife.subcommand_class_from(%w{cookbook site vendor --help foo bar baz}).should == :CookbookSiteVendor + expect(Chef::Knife.subcommand_class_from(%w{cookbook site vendor --help foo bar baz})).to eq(:CookbookSiteVendor) end end @@ -130,9 +130,9 @@ describe Chef::Knife do let(:request_mock) { {} } let(:rest) do - Net::HTTP.stub(:new).and_return(http_client) - Chef::RequestID.instance.stub(:request_id).and_return(request_id) - Chef::Config.stub(:chef_server_url).and_return("https://api.opscode.piab") + allow(Net::HTTP).to receive(:new).and_return(http_client) + allow(Chef::RequestID.instance).to receive(:request_id).and_return(request_id) + allow(Chef::Config).to receive(:chef_server_url).and_return("https://api.opscode.piab") command = Chef::Knife.run(%w{test yourself}) rest = command.noauth_rest rest @@ -140,7 +140,7 @@ describe Chef::Knife do let!(:http_client) do http_client = Net::HTTP.new(url.host, url.port) - http_client.stub(:request).and_yield(http_response).and_return(http_response) + allow(http_client).to receive(:request).and_yield(http_response).and_return(http_response) http_client end @@ -148,8 +148,8 @@ describe Chef::Knife do let(:http_response) do http_response = Net::HTTPSuccess.new("1.1", "200", "successful rest req") - http_response.stub(:read_body) - http_response.stub(:body).and_return(body) + allow(http_response).to receive(:read_body) + allow(http_response).to receive(:body).and_return(body) http_response["Content-Length"] = body.bytesize.to_s http_response end @@ -166,7 +166,7 @@ describe Chef::Knife do end it "confirms that the headers include X-Remote-Request-Id" do - Net::HTTP::Get.should_receive(:new).with("/monkey", headers).and_return(request_mock) + expect(Net::HTTP::Get).to receive(:new).with("/monkey", headers).and_return(request_mock) rest.get_rest("monkey") end end @@ -190,37 +190,37 @@ describe Chef::Knife do # there is special hackery to return the subcommand instance going on here. command = Chef::Knife.run(%w{test yourself}, extra_opts) editor_opts = command.options[:editor] - editor_opts[:long].should == "--editor EDITOR" - editor_opts[:description].should == "Set the editor to use for interactive commands" - editor_opts[:short].should == "-e EDITOR" - editor_opts[:default].should == "/usr/bin/vim" + expect(editor_opts[:long]).to eq("--editor EDITOR") + expect(editor_opts[:description]).to eq("Set the editor to use for interactive commands") + expect(editor_opts[:short]).to eq("-e EDITOR") + expect(editor_opts[:default]).to eq("/usr/bin/vim") end it "creates an instance of the subcommand and runs it" do command = Chef::Knife.run(%w{test yourself}) - command.should be_an_instance_of(KnifeSpecs::TestYourself) - command.ran.should be_true + expect(command).to be_an_instance_of(KnifeSpecs::TestYourself) + expect(command.ran).to be_truthy end it "passes the command specific args to the subcommand" do command = Chef::Knife.run(%w{test yourself with some args}) - command.name_args.should == %w{with some args} + expect(command.name_args).to eq(%w{with some args}) end it "excludes the command name from the name args when parts are joined with underscores" do command = Chef::Knife.run(%w{test_yourself with some args}) - command.name_args.should == %w{with some args} + expect(command.name_args).to eq(%w{with some args}) end it "exits if no subcommand matches the CLI args" do - Chef::Knife.ui.stub(:stderr).and_return(@stderr) - Chef::Knife.ui.should_receive(:fatal) - lambda {Chef::Knife.run(%w{fuuu uuuu fuuuu})}.should raise_error(SystemExit) { |e| e.status.should_not == 0 } + allow(Chef::Knife.ui).to receive(:stderr).and_return(@stderr) + expect(Chef::Knife.ui).to receive(:fatal) + expect {Chef::Knife.run(%w{fuuu uuuu fuuuu})}.to raise_error(SystemExit) { |e| expect(e.status).not_to eq(0) } end it "loads lazy dependencies" do Chef::Knife.run(%w{test yourself}) - KnifeSpecs::TestYourself.test_deps_loaded.should be_true + expect(KnifeSpecs::TestYourself.test_deps_loaded).to be_truthy end it "loads lazy dependencies from multiple deps calls" do @@ -230,8 +230,8 @@ describe Chef::Knife do end Chef::Knife.run(%w{test yourself}) - KnifeSpecs::TestYourself.test_deps_loaded.should be_true - other_deps_loaded.should be_true + expect(KnifeSpecs::TestYourself.test_deps_loaded).to be_truthy + expect(other_deps_loaded).to be_truthy end describe "merging configuration options" do @@ -244,21 +244,21 @@ describe Chef::Knife do it "prefers the default value if no config or command line value is present" do knife_command = KnifeSpecs::TestYourself.new([]) #empty argv knife_command.configure_chef - knife_command.config[:opt_with_default].should == "default-value" + expect(knife_command.config[:opt_with_default]).to eq("default-value") end it "prefers a value in Chef::Config[:knife] to the default" do Chef::Config[:knife][:opt_with_default] = "from-knife-config" knife_command = KnifeSpecs::TestYourself.new([]) #empty argv knife_command.configure_chef - knife_command.config[:opt_with_default].should == "from-knife-config" + expect(knife_command.config[:opt_with_default]).to eq("from-knife-config") end it "prefers a value from command line over Chef::Config and the default" do Chef::Config[:knife][:opt_with_default] = "from-knife-config" knife_command = KnifeSpecs::TestYourself.new(["-D", "from-cli"]) knife_command.configure_chef - knife_command.config[:opt_with_default].should == "from-cli" + expect(knife_command.config[:opt_with_default]).to eq("from-cli") end context "verbosity is greater than zero" do @@ -290,15 +290,15 @@ describe Chef::Knife do end it "it parses the options passed to it" do - @knife.config[:scro].should == 'scrogramming' + expect(@knife.config[:scro]).to eq('scrogramming') end it "extracts its command specific args from the full arg list" do - @knife.name_args.should == %w{with some args} + expect(@knife.name_args).to eq(%w{with some args}) end it "does not have lazy dependencies loaded" do - @knife.class.test_deps_loaded.should_not be_true + expect(@knife.class.test_deps_loaded).not_to be_truthy end end @@ -306,114 +306,114 @@ describe Chef::Knife do before do @stdout, @stderr, @stdin = StringIO.new, StringIO.new, StringIO.new @knife.ui = Chef::Knife::UI.new(@stdout, @stderr, @stdin, {}) - @knife.should_receive(:exit).with(100) + expect(@knife).to receive(:exit).with(100) end it "formats 401s nicely" do response = Net::HTTPUnauthorized.new("1.1", "401", "Unauthorized") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "y u no syncronize your clock?")) - @knife.stub(:run).and_raise(Net::HTTPServerException.new("401 Unauthorized", response)) + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "y u no syncronize your clock?")) + allow(@knife).to receive(:run).and_raise(Net::HTTPServerException.new("401 Unauthorized", response)) @knife.run_with_pretty_exceptions - @stderr.string.should match(/ERROR: Failed to authenticate to/) - @stderr.string.should match(/Response: y u no syncronize your clock\?/) + expect(@stderr.string).to match(/ERROR: Failed to authenticate to/) + expect(@stderr.string).to match(/Response: y u no syncronize your clock\?/) end it "formats 403s nicely" do response = Net::HTTPForbidden.new("1.1", "403", "Forbidden") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "y u no administrator")) - @knife.stub(:run).and_raise(Net::HTTPServerException.new("403 Forbidden", response)) - @knife.stub(:username).and_return("sadpanda") + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "y u no administrator")) + allow(@knife).to receive(:run).and_raise(Net::HTTPServerException.new("403 Forbidden", response)) + allow(@knife).to receive(:username).and_return("sadpanda") @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: You authenticated successfully to http.+ as sadpanda but you are not authorized for this action]) - @stderr.string.should match(%r[Response: y u no administrator]) + expect(@stderr.string).to match(%r[ERROR: You authenticated successfully to http.+ as sadpanda but you are not authorized for this action]) + expect(@stderr.string).to match(%r[Response: y u no administrator]) end it "formats 400s nicely" do response = Net::HTTPBadRequest.new("1.1", "400", "Bad Request") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "y u search wrong")) - @knife.stub(:run).and_raise(Net::HTTPServerException.new("400 Bad Request", response)) + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "y u search wrong")) + allow(@knife).to receive(:run).and_raise(Net::HTTPServerException.new("400 Bad Request", response)) @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: The data in your request was invalid]) - @stderr.string.should match(%r[Response: y u search wrong]) + expect(@stderr.string).to match(%r[ERROR: The data in your request was invalid]) + expect(@stderr.string).to match(%r[Response: y u search wrong]) end it "formats 404s nicely" do response = Net::HTTPNotFound.new("1.1", "404", "Not Found") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "nothing to see here")) - @knife.stub(:run).and_raise(Net::HTTPServerException.new("404 Not Found", response)) + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "nothing to see here")) + allow(@knife).to receive(:run).and_raise(Net::HTTPServerException.new("404 Not Found", response)) @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: The object you are looking for could not be found]) - @stderr.string.should match(%r[Response: nothing to see here]) + expect(@stderr.string).to match(%r[ERROR: The object you are looking for could not be found]) + expect(@stderr.string).to match(%r[Response: nothing to see here]) end it "formats 500s nicely" do response = Net::HTTPInternalServerError.new("1.1", "500", "Internal Server Error") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "sad trombone")) - @knife.stub(:run).and_raise(Net::HTTPFatalError.new("500 Internal Server Error", response)) + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "sad trombone")) + allow(@knife).to receive(:run).and_raise(Net::HTTPFatalError.new("500 Internal Server Error", response)) @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: internal server error]) - @stderr.string.should match(%r[Response: sad trombone]) + expect(@stderr.string).to match(%r[ERROR: internal server error]) + expect(@stderr.string).to match(%r[Response: sad trombone]) end it "formats 502s nicely" do response = Net::HTTPBadGateway.new("1.1", "502", "Bad Gateway") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "sadder trombone")) - @knife.stub(:run).and_raise(Net::HTTPFatalError.new("502 Bad Gateway", response)) + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "sadder trombone")) + allow(@knife).to receive(:run).and_raise(Net::HTTPFatalError.new("502 Bad Gateway", response)) @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: bad gateway]) - @stderr.string.should match(%r[Response: sadder trombone]) + expect(@stderr.string).to match(%r[ERROR: bad gateway]) + expect(@stderr.string).to match(%r[Response: sadder trombone]) end it "formats 503s nicely" do response = Net::HTTPServiceUnavailable.new("1.1", "503", "Service Unavailable") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "saddest trombone")) - @knife.stub(:run).and_raise(Net::HTTPFatalError.new("503 Service Unavailable", response)) + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "saddest trombone")) + allow(@knife).to receive(:run).and_raise(Net::HTTPFatalError.new("503 Service Unavailable", response)) @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: Service temporarily unavailable]) - @stderr.string.should match(%r[Response: saddest trombone]) + expect(@stderr.string).to match(%r[ERROR: Service temporarily unavailable]) + expect(@stderr.string).to match(%r[Response: saddest trombone]) end it "formats other HTTP errors nicely" do response = Net::HTTPPaymentRequired.new("1.1", "402", "Payment Required") response.instance_variable_set(:@read, true) # I hate you, net/http. - response.stub(:body).and_return(Chef::JSONCompat.to_json(:error => "nobugfixtillyoubuy")) - @knife.stub(:run).and_raise(Net::HTTPServerException.new("402 Payment Required", response)) + allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "nobugfixtillyoubuy")) + allow(@knife).to receive(:run).and_raise(Net::HTTPServerException.new("402 Payment Required", response)) @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: Payment Required]) - @stderr.string.should match(%r[Response: nobugfixtillyoubuy]) + expect(@stderr.string).to match(%r[ERROR: Payment Required]) + expect(@stderr.string).to match(%r[Response: nobugfixtillyoubuy]) end it "formats NameError and NoMethodError nicely" do - @knife.stub(:run).and_raise(NameError.new("Undefined constant FUUU")) + allow(@knife).to receive(:run).and_raise(NameError.new("Undefined constant FUUU")) @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: knife encountered an unexpected error]) - @stderr.string.should match(%r[This may be a bug in the 'knife' knife command or plugin]) - @stderr.string.should match(%r[Exception: NameError: Undefined constant FUUU]) + expect(@stderr.string).to match(%r[ERROR: knife encountered an unexpected error]) + expect(@stderr.string).to match(%r[This may be a bug in the 'knife' knife command or plugin]) + expect(@stderr.string).to match(%r[Exception: NameError: Undefined constant FUUU]) end it "formats missing private key errors nicely" do - @knife.stub(:run).and_raise(Chef::Exceptions::PrivateKeyMissing.new('key not there')) - @knife.stub(:api_key).and_return("/home/root/.chef/no-key-here.pem") + allow(@knife).to receive(:run).and_raise(Chef::Exceptions::PrivateKeyMissing.new('key not there')) + allow(@knife).to receive(:api_key).and_return("/home/root/.chef/no-key-here.pem") @knife.run_with_pretty_exceptions - @stderr.string.should match(%r[ERROR: Your private key could not be loaded from /home/root/.chef/no-key-here.pem]) - @stderr.string.should match(%r[Check your configuration file and ensure that your private key is readable]) + expect(@stderr.string).to match(%r[ERROR: Your private key could not be loaded from /home/root/.chef/no-key-here.pem]) + expect(@stderr.string).to match(%r[Check your configuration file and ensure that your private key is readable]) end it "formats connection refused errors nicely" do - @knife.stub(:run).and_raise(Errno::ECONNREFUSED.new('y u no shut up')) + allow(@knife).to receive(:run).and_raise(Errno::ECONNREFUSED.new('y u no shut up')) @knife.run_with_pretty_exceptions # Errno::ECONNREFUSED message differs by platform # *nix = Errno::ECONNREFUSED: Connection refused # win32: Errno::ECONNREFUSED: No connection could be made because the target machine actively refused it. - @stderr.string.should match(%r[ERROR: Network Error: .* - y u no shut up]) - @stderr.string.should match(%r[Check your knife configuration and network settings]) + expect(@stderr.string).to match(%r[ERROR: Network Error: .* - y u no shut up]) + expect(@stderr.string).to match(%r[Check your knife configuration and network settings]) end end diff --git a/spec/unit/lwrp_spec.rb b/spec/unit/lwrp_spec.rb index 452e1da2a4..0fb0ea7cab 100644 --- a/spec/unit/lwrp_spec.rb +++ b/spec/unit/lwrp_spec.rb @@ -33,7 +33,7 @@ describe "LWRP" do describe "when overriding an existing class" do before :each do - $stderr.stub(:write) + allow($stderr).to receive(:write) end it "should log if attempting to load resource of same name" do @@ -42,8 +42,8 @@ describe "LWRP" do end Dir[File.expand_path( "lwrp/resources/*", CHEF_SPEC_DATA)].each do |file| - Chef::Log.should_receive(:info).with(/Skipping/) - Chef::Log.should_receive(:debug).with(/anymore/) + expect(Chef::Log).to receive(:info).with(/Skipping/) + expect(Chef::Log).to receive(:debug).with(/anymore/) Chef::Resource::LWRPBase.build_from_file("lwrp", file, nil) end end @@ -54,8 +54,8 @@ describe "LWRP" do end Dir[File.expand_path( "lwrp/providers/*", CHEF_SPEC_DATA)].each do |file| - Chef::Log.should_receive(:info).with(/Skipping/) - Chef::Log.should_receive(:debug).with(/anymore/) + expect(Chef::Log).to receive(:info).with(/Skipping/) + expect(Chef::Log).to receive(:debug).with(/anymore/) Chef::Provider::LWRPBase.build_from_file("lwrp", file, nil) end end @@ -67,11 +67,11 @@ describe "LWRP" do Chef::Resource::LWRPBase.build_from_file("lwrp", file, nil) end first_lwr_foo_class = Chef::Resource::LwrpFoo - Chef::Resource.resource_classes.should include(first_lwr_foo_class) + expect(Chef::Resource.resource_classes).to include(first_lwr_foo_class) Dir[File.expand_path( "lwrp/resources/*", CHEF_SPEC_DATA)].each do |file| Chef::Resource::LWRPBase.build_from_file("lwrp", file, nil) end - Chef::Resource.resource_classes.should include(first_lwr_foo_class) + expect(Chef::Resource.resource_classes).to include(first_lwr_foo_class) end it "does not attempt to remove classes from higher up namespaces [CHEF-4117]" do @@ -95,27 +95,27 @@ describe "LWRP" do end it "should load the resource into a properly-named class" do - Chef::Resource.const_get("LwrpFoo").should be_kind_of(Class) + expect(Chef::Resource.const_get("LwrpFoo")).to be_kind_of(Class) end it "should set resource_name" do - Chef::Resource::LwrpFoo.new("blah").resource_name.should eql(:lwrp_foo) + expect(Chef::Resource::LwrpFoo.new("blah").resource_name).to eql(:lwrp_foo) end it "should add the specified actions to the allowed_actions array" do - Chef::Resource::LwrpFoo.new("blah").allowed_actions.should include(:pass_buck, :twiddle_thumbs) + expect(Chef::Resource::LwrpFoo.new("blah").allowed_actions).to include(:pass_buck, :twiddle_thumbs) end it "should set the specified action as the default action" do - Chef::Resource::LwrpFoo.new("blah").action.should == :pass_buck + expect(Chef::Resource::LwrpFoo.new("blah").action).to eq(:pass_buck) end it "should create a method for each attribute" do - Chef::Resource::LwrpFoo.new("blah").methods.map{ |m| m.to_sym}.should include(:monkey) + expect(Chef::Resource::LwrpFoo.new("blah").methods.map{ |m| m.to_sym}).to include(:monkey) end it "should build attribute methods that respect validation rules" do - lambda { Chef::Resource::LwrpFoo.new("blah").monkey(42) }.should raise_error(ArgumentError) + expect { Chef::Resource::LwrpFoo.new("blah").monkey(42) }.to raise_error(ArgumentError) end it "should have access to the run context and node during class definition" do @@ -128,9 +128,9 @@ describe "LWRP" do end cls = Chef::Resource.const_get("LwrpNodeattr") - cls.node.should be_kind_of(Chef::Node) - cls.run_context.should be_kind_of(Chef::RunContext) - cls.node[:penguin_name].should eql("jackass") + expect(cls.node).to be_kind_of(Chef::Node) + expect(cls.run_context).to be_kind_of(Chef::RunContext) + expect(cls.node[:penguin_name]).to eql("jackass") end context "resource_name" do @@ -296,13 +296,13 @@ describe "LWRP" do end it "should load the provider into a properly-named class" do - Chef::Provider.const_get("LwrpBuckPasser").should be_kind_of(Class) + expect(Chef::Provider.const_get("LwrpBuckPasser")).to be_kind_of(Class) end it "should create a method for each attribute" do new_resource = double("new resource").as_null_object - Chef::Provider::LwrpBuckPasser.new(nil, new_resource).methods.map{|m|m.to_sym}.should include(:action_pass_buck) - Chef::Provider::LwrpThumbTwiddler.new(nil, new_resource).methods.map{|m|m.to_sym}.should include(:action_twiddle_thumbs) + expect(Chef::Provider::LwrpBuckPasser.new(nil, new_resource).methods.map{|m|m.to_sym}).to include(:action_pass_buck) + expect(Chef::Provider::LwrpThumbTwiddler.new(nil, new_resource).methods.map{|m|m.to_sym}).to include(:action_twiddle_thumbs) end it "should insert resources embedded in the provider into the middle of the resource collection" do @@ -316,10 +316,10 @@ describe "LWRP" do Chef::Runner.new(@run_context).converge - @run_context.resource_collection[0].should eql(injector) - @run_context.resource_collection[1].name.should eql(:prepared_thumbs) - @run_context.resource_collection[2].name.should eql(:twiddled_thumbs) - @run_context.resource_collection[3].should eql(dummy) + expect(@run_context.resource_collection[0]).to eql(injector) + expect(@run_context.resource_collection[1].name).to eql(:prepared_thumbs) + expect(@run_context.resource_collection[2].name).to eql(:twiddled_thumbs) + expect(@run_context.resource_collection[3]).to eql(dummy) end it "should insert embedded resources from multiple providers, including from the last position, properly into the resource collection" do @@ -340,13 +340,13 @@ describe "LWRP" do Chef::Runner.new(@run_context).converge - @run_context.resource_collection[0].should eql(injector) - @run_context.resource_collection[1].name.should eql(:prepared_thumbs) - @run_context.resource_collection[2].name.should eql(:twiddled_thumbs) - @run_context.resource_collection[3].should eql(dummy) - @run_context.resource_collection[4].should eql(injector2) - @run_context.resource_collection[5].name.should eql(:prepared_eyes) - @run_context.resource_collection[6].name.should eql(:dried_paint_watched) + expect(@run_context.resource_collection[0]).to eql(injector) + expect(@run_context.resource_collection[1].name).to eql(:prepared_thumbs) + expect(@run_context.resource_collection[2].name).to eql(:twiddled_thumbs) + expect(@run_context.resource_collection[3]).to eql(dummy) + expect(@run_context.resource_collection[4]).to eql(injector2) + expect(@run_context.resource_collection[5].name).to eql(:prepared_eyes) + expect(@run_context.resource_collection[6].name).to eql(:dried_paint_watched) end it "should properly handle a new_resource reference" do @@ -357,7 +357,7 @@ describe "LWRP" do provider = Chef::Platform.provider_for_resource(resource, :twiddle_thumbs) provider.action_twiddle_thumbs - provider.monkey_name.should == "my monkey's name is 'bob'" + expect(provider.monkey_name).to eq("my monkey's name is 'bob'") end it "should properly handle an embedded Resource accessing the enclosing Provider's scope" do @@ -369,7 +369,7 @@ describe "LWRP" do #provider = @runner.build_provider(resource) provider.action_twiddle_thumbs - provider.enclosed_resource.monkey.should == 'bob, the monkey' + expect(provider.enclosed_resource.monkey).to eq('bob, the monkey') end describe "when using inline compilation" do @@ -388,27 +388,27 @@ describe "LWRP" do it "does not add interior resources to the exterior resource collection" do @resource.run_action(:test) - @run_context.resource_collection.should be_empty + expect(@run_context.resource_collection).to be_empty end context "when interior resources are updated" do it "processes notifications within the LWRP provider's action" do @resource.run_action(:test) - $interior_ruby_block_2.should == "executed" + expect($interior_ruby_block_2).to eq("executed") end it "marks the parent resource updated" do @resource.run_action(:test) - @resource.should be_updated - @resource.should be_updated_by_last_action + expect(@resource).to be_updated + expect(@resource).to be_updated_by_last_action end end context "when interior resources are not updated" do it "does not mark the parent resource updated" do @resource.run_action(:no_updates) - @resource.should_not be_updated - @resource.should_not be_updated_by_last_action + expect(@resource).not_to be_updated + expect(@resource).not_to be_updated_by_last_action end end diff --git a/spec/unit/mash_spec.rb b/spec/unit/mash_spec.rb index 7358781e60..b8f4c2d5aa 100644 --- a/spec/unit/mash_spec.rb +++ b/spec/unit/mash_spec.rb @@ -24,27 +24,27 @@ describe Mash do data = {:x=>"one", :y=>"two", :z=>"three"} @orig = Mash.new(data) @copy = @orig.dup - @copy.to_hash.should == Mash.new(data).to_hash + expect(@copy.to_hash).to eq(Mash.new(data).to_hash) @copy[:x] = "four" - @orig[:x].should == "one" + expect(@orig[:x]).to eq("one") end it "should duplicate a mash with an array to a new mash" do data = {:x=>"one", :y=>"two", :z=>[1,2,3]} @orig = Mash.new(data) @copy = @orig.dup - @copy.to_hash.should == Mash.new(data).to_hash + expect(@copy.to_hash).to eq(Mash.new(data).to_hash) @copy[:z] << 4 - @orig[:z].should == [1,2,3] + expect(@orig[:z]).to eq([1,2,3]) end it "should duplicate a nested mash to a new mash" do data = {:x=>"one", :y=>"two", :z=>Mash.new({:a=>[1,2,3]})} @orig = Mash.new(data) @copy = @orig.dup - @copy.to_hash.should == Mash.new(data).to_hash + expect(@copy.to_hash).to eq(Mash.new(data).to_hash) @copy[:z][:a] << 4 - @orig[:z][:a].should == [1,2,3] + expect(@orig[:z][:a]).to eq([1,2,3]) end # add more! diff --git a/spec/unit/mixin/checksum_spec.rb b/spec/unit/mixin/checksum_spec.rb index 54689c9992..864b15f2bc 100644 --- a/spec/unit/mixin/checksum_spec.rb +++ b/spec/unit/mixin/checksum_spec.rb @@ -30,11 +30,11 @@ describe Chef::Mixin::Checksum do @cache = Chef::Digester.instance @file = CHEF_SPEC_DATA + "/checksum/random.txt" @stat = double("File::Stat", { :mtime => Time.at(0) }) - File.stub(:stat).and_return(@stat) + allow(File).to receive(:stat).and_return(@stat) end it "gets the checksum of a file" do - @checksum_user.checksum(@file).should == "09ee9c8cc70501763563bcf9c218d71b2fbf4186bf8e1e0da07f0f42c80a3394" + expect(@checksum_user.checksum(@file)).to eq("09ee9c8cc70501763563bcf9c218d71b2fbf4186bf8e1e0da07f0f42c80a3394") end end diff --git a/spec/unit/mixin/command_spec.rb b/spec/unit/mixin/command_spec.rb index 96660be436..e198e3addd 100644 --- a/spec/unit/mixin/command_spec.rb +++ b/spec/unit/mixin/command_spec.rb @@ -31,41 +31,41 @@ describe Chef::Mixin::Command, :volatile do it "should be possible to read the child process's stdout and stderr" do popen4("sh -c 'echo hello && echo world >&2'") do |pid, stdin, stdout, stderr| - stdout.read.should == "hello\n" - stderr.read.should == "world\n" + expect(stdout.read).to eq("hello\n") + expect(stderr.read).to eq("world\n") end end it "should default all commands to be run in the POSIX standard C locale" do popen4("echo $LC_ALL") do |pid, stdin, stdout, stderr| - stdout.read.strip.should == "C" + expect(stdout.read.strip).to eq("C") end end it "should respect locale when specified explicitly" do popen4("echo $LC_ALL", :environment => {"LC_ALL" => "es"}) do |pid, stdin, stdout, stderr| - stdout.read.strip.should == "es" + expect(stdout.read.strip).to eq("es") end end it "should end when the child process reads from STDIN and a block is given" do - lambda {Timeout.timeout(10) do + expect {Timeout.timeout(10) do popen4("ruby -e 'while gets; end'", :waitlast => true) do |pid, stdin, stdout, stderr| (1..5).each { |i| stdin.puts "#{i}" } end end - }.should_not raise_error + }.not_to raise_error end describe "when a process detaches but doesn't close STDOUT and STDERR [CHEF-584]" do it "returns immediately after the first child process exits" do - lambda {Timeout.timeout(10) do + expect {Timeout.timeout(10) do pid, stdin,stdout,stderr = nil,nil,nil,nil evil_forker="exit if fork; 10.times { sleep 1}" popen4("ruby -e '#{evil_forker}'") do |pid,stdin,stdout,stderr| end - end}.should_not raise_error + end}.not_to raise_error end end @@ -76,13 +76,13 @@ describe Chef::Mixin::Command, :volatile do include Chef::Mixin::Command it "logs the command's stderr and stdout output if the command failed" do - Chef::Log.stub(:level).and_return(:debug) + allow(Chef::Log).to receive(:level).and_return(:debug) begin run_command(:command => "sh -c 'echo hello; echo world >&2; false'") violated "Exception expected, but nothing raised." rescue => e - e.message.should =~ /STDOUT: hello/ - e.message.should =~ /STDERR: world/ + expect(e.message).to match(/STDOUT: hello/) + expect(e.message).to match(/STDERR: world/) end end @@ -93,10 +93,10 @@ describe Chef::Mixin::Command, :volatile do # btm # Serdar - During Solaris tests, we've seen that processes # are taking a long time to exit. Bumping timeout now to 10. - lambda {Timeout.timeout(10) do + expect {Timeout.timeout(10) do evil_forker="exit if fork; 10.times { sleep 1}" run_command(:command => "ruby -e '#{evil_forker}'") - end}.should_not raise_error + end}.not_to raise_error end end diff --git a/spec/unit/mixin/convert_to_class_name_spec.rb b/spec/unit/mixin/convert_to_class_name_spec.rb index 0276a55fd7..4cf6728d64 100644 --- a/spec/unit/mixin/convert_to_class_name_spec.rb +++ b/spec/unit/mixin/convert_to_class_name_spec.rb @@ -29,26 +29,26 @@ describe Chef::Mixin::ConvertToClassName do end it "converts a_snake_case_word to a CamelCaseWord" do - @convert.convert_to_class_name("now_camelized").should == "NowCamelized" + expect(@convert.convert_to_class_name("now_camelized")).to eq("NowCamelized") end it "converts a CamelCaseWord to a snake_case_word" do - @convert.convert_to_snake_case("NowImASnake").should == "now_im_a_snake" + expect(@convert.convert_to_snake_case("NowImASnake")).to eq("now_im_a_snake") end it "removes the base classes before snake casing" do - @convert.convert_to_snake_case("NameSpaced::Class::ThisIsWin", "NameSpaced::Class").should == "this_is_win" + expect(@convert.convert_to_snake_case("NameSpaced::Class::ThisIsWin", "NameSpaced::Class")).to eq("this_is_win") end it "removes the base classes without explicitly naming them and returns snake case" do - @convert.snake_case_basename("NameSpaced::Class::ExtraWin").should == "extra_win" + expect(@convert.snake_case_basename("NameSpaced::Class::ExtraWin")).to eq("extra_win") end it "interprets non-alphanumeric characters in snake case as word boundaries" do - @convert.convert_to_class_name("now_camelized_without-hyphen").should == "NowCamelizedWithoutHyphen" + expect(@convert.convert_to_class_name("now_camelized_without-hyphen")).to eq("NowCamelizedWithoutHyphen") end it "interprets underscore" do - @convert.convert_to_class_name("_remove_leading_underscore").should == "RemoveLeadingUnderscore" + expect(@convert.convert_to_class_name("_remove_leading_underscore")).to eq("RemoveLeadingUnderscore") end end diff --git a/spec/unit/mixin/deep_merge_spec.rb b/spec/unit/mixin/deep_merge_spec.rb index dbc49e68f2..40e749ecc0 100644 --- a/spec/unit/mixin/deep_merge_spec.rb +++ b/spec/unit/mixin/deep_merge_spec.rb @@ -37,175 +37,175 @@ describe Chef::Mixin::DeepMerge, "deep_merge!" do hash_src = {'id' => '2'} hash_dst = {} @dm.deep_merge!(hash_src.dup, hash_dst) - hash_dst.should == hash_src + expect(hash_dst).to eq(hash_src) end it "tests merging an hash w/array into blank hash" do hash_src = {'region' => {'id' => ['227', '2']}} hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == hash_src + expect(hash_dst).to eq(hash_src) end it "tests merge from empty hash" do hash_src = {} hash_dst = {"property" => ["2","4"]} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => ["2","4"]} + expect(hash_dst).to eq({"property" => ["2","4"]}) end it "tests merge to empty hash" do hash_src = {"property" => ["2","4"]} hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => ["2","4"]} + expect(hash_dst).to eq({"property" => ["2","4"]}) end it "tests simple string overwrite" do hash_src = {"name" => "value"} hash_dst = {"name" => "value1"} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"name" => "value"} + expect(hash_dst).to eq({"name" => "value"}) end it "tests simple string overwrite of empty hash" do hash_src = {"name" => "value"} hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == hash_src + expect(hash_dst).to eq(hash_src) end it "tests hashes holding array" do hash_src = {"property" => ["1","3"]} hash_dst = {"property" => ["2","4"]} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => ["2","4","1","3"]} + expect(hash_dst).to eq({"property" => ["2","4","1","3"]}) end it "tests hashes holding hashes holding arrays (array with duplicate elements is merged with dest then src" do hash_src = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["1", "4+"]}} hash_dst = {"property" => {"bedroom_count" => ["3", "2"], "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => ["3","2","1"], "bathroom_count" => ["2", "1", "4+"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => ["3","2","1"], "bathroom_count" => ["2", "1", "4+"]}}) end it "tests hash holding hash holding array v string (string is overwritten by array)" do hash_src = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["1", "4+"]}} hash_dst = {"property" => {"bedroom_count" => "3", "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["2","1","4+"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["2","1","4+"]}}) end it "tests hash holding hash holding string v array (array is overwritten by string)" do hash_src = {"property" => {"bedroom_count" => "3", "bathroom_count" => ["1", "4+"]}} hash_dst = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => "3", "bathroom_count" => ["2","1","4+"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => "3", "bathroom_count" => ["2","1","4+"]}}) end it "tests hash holding hash holding hash v array (array is overwritten by hash)" do hash_src = {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["1", "4+"]}} hash_dst = {"property" => {"bedroom_count" => ["1", "2"], "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["2","1","4+"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["2","1","4+"]}}) end it "tests 3 hash layers holding integers (integers are overwritten by source)" do hash_src = {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["1", "4+"]}} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => 2, "queen_bed" => 4}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["2","1","4+"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => 1}, "bathroom_count" => ["2","1","4+"]}}) end it "tests 3 hash layers holding arrays of int (arrays are merged)" do hash_src = {"property" => {"bedroom_count" => {"king_bed" => [3], "queen_bed" => [1]}, "bathroom_count" => ["1", "4+"]}} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4,1]}, "bathroom_count" => ["2","1","4+"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4,1]}, "bathroom_count" => ["2","1","4+"]}}) end it "tests 1 hash overwriting 3 hash layers holding arrays of int" do hash_src = {"property" => "1"} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => "1"} + expect(hash_dst).to eq({"property" => "1"}) end it "tests 3 hash layers holding arrays of int (arrays are merged) but second hash's array is overwritten" do hash_src = {"property" => {"bedroom_count" => {"king_bed" => [3], "queen_bed" => [1]}, "bathroom_count" => "1"}} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4,1]}, "bathroom_count" => "1"}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4,1]}, "bathroom_count" => "1"}}) end it "tests 3 hash layers holding arrays of int, but one holds int. This one overwrites, but the rest merge" do hash_src = {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => [1]}, "bathroom_count" => ["1"]}} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => [4,1]}, "bathroom_count" => ["2","1"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => 3, "queen_bed" => [4,1]}, "bathroom_count" => ["2","1"]}}) end it "tests 3 hash layers holding arrays of int, but source is incomplete." do hash_src = {"property" => {"bedroom_count" => {"king_bed" => [3]}, "bathroom_count" => ["1"]}} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4]}, "bathroom_count" => ["2","1"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2,3], "queen_bed" => [4]}, "bathroom_count" => ["2","1"]}}) end it "tests 3 hash layers holding arrays of int, but source is shorter and has new 2nd level ints." do hash_src = {"property" => {"bedroom_count" => {2=>3, "king_bed" => [3]}, "bathroom_count" => ["1"]}} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {2=>3, "king_bed" => [2,3], "queen_bed" => [4]}, "bathroom_count" => ["2","1"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {2=>3, "king_bed" => [2,3], "queen_bed" => [4]}, "bathroom_count" => ["2","1"]}}) end it "tests 3 hash layers holding arrays of int, but source is empty" do hash_src = {} hash_dst = {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {"king_bed" => [2], "queen_bed" => [4]}, "bathroom_count" => ["2"]}}) end it "tests 3 hash layers holding arrays of int, but dest is empty" do hash_src = {"property" => {"bedroom_count" => {2=>3, "king_bed" => [3]}, "bathroom_count" => ["1"]}} hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"property" => {"bedroom_count" => {2=>3, "king_bed" => [3]}, "bathroom_count" => ["1"]}} + expect(hash_dst).to eq({"property" => {"bedroom_count" => {2=>3, "king_bed" => [3]}, "bathroom_count" => ["1"]}}) end it "tests hash holding arrays of arrays" do hash_src = {["1", "2", "3"] => ["1", "2"]} hash_dst = {["4", "5"] => ["3"]} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {["1","2","3"] => ["1", "2"], ["4", "5"] => ["3"]} + expect(hash_dst).to eq({["1","2","3"] => ["1", "2"], ["4", "5"] => ["3"]}) end it "tests merging of hash with blank hash, and make sure that source array split does not function when turned off" do hash_src = {'property' => {'bedroom_count' => ["1","2,3"]}} hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {'property' => {'bedroom_count' => ["1","2,3"]}} + expect(hash_dst).to eq({'property' => {'bedroom_count' => ["1","2,3"]}}) end it "tests merging into a blank hash" do hash_src = {"action"=>"browse", "controller"=>"results"} hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == hash_src + expect(hash_dst).to eq(hash_src) end it "tests are unmerged hashes passed unmodified w/out :unpack_arrays?" do hash_src = {"amenity"=>{"id"=>["26,27"]}} hash_dst = {} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"amenity"=>{"id"=>["26,27"]}} + expect(hash_dst).to eq({"amenity"=>{"id"=>["26,27"]}}) end it "tests hash of array of hashes" do hash_src = {"item" => [{"1" => "3"}, {"2" => "4"}]} hash_dst = {"item" => [{"3" => "5"}]} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"item" => [{"3" => "5"}, {"1" => "3"}, {"2" => "4"}]} + expect(hash_dst).to eq({"item" => [{"3" => "5"}, {"1" => "3"}, {"2" => "4"}]}) end # Additions since import @@ -213,42 +213,42 @@ describe Chef::Mixin::DeepMerge, "deep_merge!" do hash_src = {"valid" => false} hash_dst = {"valid" => true} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"valid" => false} + expect(hash_dst).to eq({"valid" => false}) end it "should overwrite false with true when merging boolean values" do hash_src = {"valid" => true} hash_dst = {"valid" => false} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"valid" => true} + expect(hash_dst).to eq({"valid" => true}) end it "should overwrite a string with an empty string when merging string values" do hash_src = {"item" => " "} hash_dst = {"item" => "orange"} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"item" => " "} + expect(hash_dst).to eq({"item" => " "}) end it "should overwrite an empty string with a string when merging string values" do hash_src = {"item" => "orange"} hash_dst = {"item" => " "} @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"item" => "orange"} + expect(hash_dst).to eq({"item" => "orange"}) end it 'should overwrite hashes with nil' do hash_src = {"item" => { "1" => "2"}, "other" => true } hash_dst = {"item" => nil } @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"item" => nil, "other" => true } + expect(hash_dst).to eq({"item" => nil, "other" => true }) end it 'should overwrite strings with nil' do hash_src = {"item" => "to_overwrite", "other" => false } hash_dst = {"item" => nil } @dm.deep_merge!(hash_src, hash_dst) - hash_dst.should == {"item" => nil, "other" => false } + expect(hash_dst).to eq({"item" => nil, "other" => false }) end end # deep_merge! @@ -262,40 +262,40 @@ describe Chef::Mixin::DeepMerge do it "should merge a hash into an empty hash" do hash_dst = {} hash_src = {'id' => '2'} - @dm.merge(hash_dst, hash_src).should == hash_src + expect(@dm.merge(hash_dst, hash_src)).to eq(hash_src) end it "should merge a nested hash into an empty hash" do hash_dst = {} hash_src = {'region' => {'id' => ['227', '2']}} - @dm.merge(hash_dst, hash_src).should == hash_src + expect(@dm.merge(hash_dst, hash_src)).to eq(hash_src) end it "should overwrite as string value when merging hashes" do hash_dst = {"name" => "value1"} hash_src = {"name" => "value"} - @dm.merge(hash_dst, hash_src).should == {"name" => "value"} + expect(@dm.merge(hash_dst, hash_src)).to eq({"name" => "value"}) end it "should merge arrays within hashes" do hash_dst = {"property" => ["2","4"]} hash_src = {"property" => ["1","3"]} - @dm.merge(hash_dst, hash_src).should == {"property" => ["2","4","1","3"]} + expect(@dm.merge(hash_dst, hash_src)).to eq({"property" => ["2","4","1","3"]}) end it "should merge deeply nested hashes" do hash_dst = {"property" => {"values" => {"are" => "falling", "can" => "change"}}} hash_src = {"property" => {"values" => {"are" => "stable", "may" => "rise"}}} - @dm.merge(hash_dst, hash_src).should == {"property" => {"values" => {"are" => "stable", "can" => "change", "may" => "rise"}}} + expect(@dm.merge(hash_dst, hash_src)).to eq({"property" => {"values" => {"are" => "stable", "can" => "change", "may" => "rise"}}}) end it "should not modify the source or destination during the merge" do hash_dst = {"property" => ["1","2","3"]} hash_src = {"property" => ["4","5","6"]} ret = @dm.merge(hash_dst, hash_src) - hash_dst.should == {"property" => ["1","2","3"]} - hash_src.should == {"property" => ["4","5","6"]} - ret.should == {"property" => ["1","2","3","4","5","6"]} + expect(hash_dst).to eq({"property" => ["1","2","3"]}) + expect(hash_src).to eq({"property" => ["4","5","6"]}) + expect(ret).to eq({"property" => ["1","2","3","4","5","6"]}) end it "should not error merging un-dupable objects" do @@ -308,25 +308,25 @@ describe Chef::Mixin::DeepMerge do it "errors out if knockout merge use is detected in an array" do hash_dst = {"property" => ["2","4"]} hash_src = {"property" => ["1","!merge:4"]} - lambda {@dm.role_merge(hash_dst, hash_src)}.should raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) + expect {@dm.role_merge(hash_dst, hash_src)}.to raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) end it "errors out if knockout merge use is detected in an array (reversed merge order)" do hash_dst = {"property" => ["1","!merge:4"]} hash_src = {"property" => ["2","4"]} - lambda {@dm.role_merge(hash_dst, hash_src)}.should raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) + expect {@dm.role_merge(hash_dst, hash_src)}.to raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) end it "errors out if knockout merge use is detected in a string" do hash_dst = {"property" => ["2","4"]} hash_src = {"property" => "!merge"} - lambda {@dm.role_merge(hash_dst, hash_src)}.should raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) + expect {@dm.role_merge(hash_dst, hash_src)}.to raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) end it "errors out if knockout merge use is detected in a string (reversed merge order)" do hash_dst = {"property" => "!merge"} hash_src= {"property" => ["2","4"]} - lambda {@dm.role_merge(hash_dst, hash_src)}.should raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) + expect {@dm.role_merge(hash_dst, hash_src)}.to raise_error(Chef::Mixin::DeepMerge::InvalidSubtractiveMerge) end end @@ -337,10 +337,10 @@ describe Chef::Mixin::DeepMerge do merged_result = @dm.hash_only_merge(merge_ee_hash, merge_with_hash) - merged_result["top_level_b"].should == "top-level-b-merged-onto" - merged_result["top_level_a"]["1_deep_a"].should == "1-a-merge-ee" - merged_result["top_level_a"]["1_deep_b"].should == "1-deep-b-merged-onto" - merged_result["top_level_a"]["1_deep_c"].should == "1-deep-c-merged-onto" + expect(merged_result["top_level_b"]).to eq("top-level-b-merged-onto") + expect(merged_result["top_level_a"]["1_deep_a"]).to eq("1-a-merge-ee") + expect(merged_result["top_level_a"]["1_deep_b"]).to eq("1-deep-b-merged-onto") + expect(merged_result["top_level_a"]["1_deep_c"]).to eq("1-deep-c-merged-onto") end it "replaces arrays rather than merging them" do @@ -349,9 +349,9 @@ describe Chef::Mixin::DeepMerge do merged_result = @dm.hash_only_merge(merge_ee_hash, merge_with_hash) - merged_result["top_level_b"].should == "top-level-b-merged-onto" - merged_result["top_level_a"]["1_deep_a"].should == "1-a-merge-ee" - merged_result["top_level_a"]["1_deep_b"].should == %w[B B B] + expect(merged_result["top_level_b"]).to eq("top-level-b-merged-onto") + expect(merged_result["top_level_a"]["1_deep_a"]).to eq("1-a-merge-ee") + expect(merged_result["top_level_a"]["1_deep_b"]).to eq(%w[B B B]) end it "replaces non-hash items with hashes when there's a conflict" do @@ -360,17 +360,17 @@ describe Chef::Mixin::DeepMerge do merged_result = @dm.hash_only_merge(merge_ee_hash, merge_with_hash) - merged_result["top_level_a"].should be_a(Hash) - merged_result["top_level_a"]["1_deep_a"].should be_nil - merged_result["top_level_a"]["1_deep_b"].should == %w[B B B] + expect(merged_result["top_level_a"]).to be_a(Hash) + expect(merged_result["top_level_a"]["1_deep_a"]).to be_nil + expect(merged_result["top_level_a"]["1_deep_b"]).to eq(%w[B B B]) end it "does not mutate deeply-nested original hashes by default" do merge_ee_hash = {"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_a" => "foo" }}}} merge_with_hash = {"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_b" => "bar" }}}} @dm.hash_only_merge(merge_ee_hash, merge_with_hash) - merge_ee_hash.should == {"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_a" => "foo" }}}} - merge_with_hash.should == {"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_b" => "bar" }}}} + expect(merge_ee_hash).to eq({"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_a" => "foo" }}}}) + expect(merge_with_hash).to eq({"top_level_a" => {"1_deep_a" => { "2_deep_a" => { "3_deep_b" => "bar" }}}}) end it "does not error merging un-dupable items" do diff --git a/spec/unit/mixin/deprecation_spec.rb b/spec/unit/mixin/deprecation_spec.rb index 3ebf06e830..6d9f39af9f 100644 --- a/spec/unit/mixin/deprecation_spec.rb +++ b/spec/unit/mixin/deprecation_spec.rb @@ -28,16 +28,16 @@ describe Chef::Mixin do end it "has a list of deprecated constants" do - Chef::Mixin.deprecated_constants.should have_key(:DeprecatedClass) + expect(Chef::Mixin.deprecated_constants).to have_key(:DeprecatedClass) end it "returns the replacement when accessing the deprecated constant" do - Chef::Mixin::DeprecatedClass.should == Chef::Node + expect(Chef::Mixin::DeprecatedClass).to eq(Chef::Node) end it "warns when accessing the deprecated constant" do Chef::Mixin::DeprecatedClass - @log_io.string.should include("This is a test deprecation") + expect(@log_io.string).to include("This is a test deprecation") end end end @@ -50,8 +50,8 @@ describe Chef::Mixin::Deprecation::DeprecatedInstanceVariable do end it "forward method calls to the target object" do - @deprecated_ivar.length.should == 5 - @deprecated_ivar.to_sym.should == :value + expect(@deprecated_ivar.length).to eq(5) + expect(@deprecated_ivar.to_sym).to eq(:value) end end diff --git a/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb b/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb index fe72d53de5..aeef175ff9 100644 --- a/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb +++ b/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb @@ -40,15 +40,15 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do end it "should call set_all on the file access control object" do - Chef::FileAccessControl.any_instance.should_receive(:set_all) + expect_any_instance_of(Chef::FileAccessControl).to receive(:set_all) @provider.enforce_ownership_and_permissions end context "when nothing was updated" do before do - Chef::FileAccessControl.any_instance.stub(:uid_from_resource).and_return(0) - Chef::FileAccessControl.any_instance.stub(:requires_changes?).and_return(false) - Chef::FileAccessControl.any_instance.stub(:define_resource_requirements) + allow_any_instance_of(Chef::FileAccessControl).to receive(:uid_from_resource).and_return(0) + allow_any_instance_of(Chef::FileAccessControl).to receive(:requires_changes?).and_return(false) + allow_any_instance_of(Chef::FileAccessControl).to receive(:define_resource_requirements) passwd_struct = if windows? Struct::Passwd.new("root", "x", 0, 0, "/root", "/bin/bash") @@ -56,14 +56,14 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do Struct::Passwd.new("root", "x", 0, 0, "root", "/root", "/bin/bash") end group_struct = OpenStruct.new(:name => "root", :passwd => "x", :gid => 0) - Etc.stub(:getpwuid).and_return(passwd_struct) - Etc.stub(:getgrgid).and_return(group_struct) + allow(Etc).to receive(:getpwuid).and_return(passwd_struct) + allow(Etc).to receive(:getgrgid).and_return(group_struct) end it "does not set updated_by_last_action on the new resource" do - @provider.new_resource.should_not_receive(:updated_by_last_action) + expect(@provider.new_resource).not_to receive(:updated_by_last_action) - Chef::FileAccessControl.any_instance.stub(:set_all) + allow_any_instance_of(Chef::FileAccessControl).to receive(:set_all) @provider.run_action(:create) end @@ -71,8 +71,8 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do context "when something was modified" do before do - Chef::FileAccessControl.any_instance.stub(:requires_changes?).and_return(true) - Chef::FileAccessControl.any_instance.stub(:uid_from_resource).and_return(0) + allow_any_instance_of(Chef::FileAccessControl).to receive(:requires_changes?).and_return(true) + allow_any_instance_of(Chef::FileAccessControl).to receive(:uid_from_resource).and_return(0) passwd_struct = if windows? Struct::Passwd.new("root", "x", 0, 0, "/root", "/bin/bash") @@ -80,15 +80,15 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do Struct::Passwd.new("root", "x", 0, 0, "root", "/root", "/bin/bash") end group_struct = OpenStruct.new(:name => "root", :passwd => "x", :gid => 0) - Etc.stub(:getpwuid).and_return(passwd_struct) - Etc.stub(:getgrgid).and_return(group_struct) + allow(Etc).to receive(:getpwuid).and_return(passwd_struct) + allow(Etc).to receive(:getgrgid).and_return(group_struct) end it "sets updated_by_last_action on the new resource" do @provider.new_resource.owner(0) # CHEF-3557 hack - Set these because we don't for windows @provider.new_resource.group(0) # CHEF-3557 hack - Set these because we don't for windows - @provider.new_resource.should_receive(:updated_by_last_action) - Chef::FileAccessControl.any_instance.stub(:set_all) + expect(@provider.new_resource).to receive(:updated_by_last_action) + allow_any_instance_of(Chef::FileAccessControl).to receive(:set_all) @provider.run_action(:create) end end diff --git a/spec/unit/mixin/homebrew_user_spec.rb b/spec/unit/mixin/homebrew_user_spec.rb index 4e30455765..57b89720dc 100644 --- a/spec/unit/mixin/homebrew_user_spec.rb +++ b/spec/unit/mixin/homebrew_user_spec.rb @@ -41,7 +41,7 @@ describe Chef::Mixin::HomebrewUser do it 'returns the homebrew user without looking at the file when name is provided' do expect(File).to receive(:exist?).exactly(0).times - Etc.stub_chain(:getpwnam, :uid).and_return(uid) + allow(Etc).to receive_message_chain(:getpwnam, :uid).and_return(uid) expect(homebrew_user.find_homebrew_uid(user)).to eq(uid) end @@ -71,7 +71,7 @@ describe Chef::Mixin::HomebrewUser do it 'returns the owner of the brew executable when it is not at a default location' do expect(File).to receive(:exist?).with(default_brew_path).and_return(false) - homebrew_user.stub_chain(:shell_out, :stdout, :strip).and_return("/foo") + allow(homebrew_user).to receive_message_chain(:shell_out, :stdout, :strip).and_return("/foo") expect(File).to receive(:stat).with("/foo").and_return(stat_double) expect(homebrew_user.find_homebrew_uid(user)).to eq(brew_owner) end @@ -83,7 +83,7 @@ describe Chef::Mixin::HomebrewUser do it 'raises an error if no executable is found' do expect(File).to receive(:exist?).with(default_brew_path).and_return(false) - homebrew_user.stub_chain(:shell_out, :stdout, :strip).and_return("") + allow(homebrew_user).to receive_message_chain(:shell_out, :stdout, :strip).and_return("") expect { homebrew_user.find_homebrew_uid(user) }.to raise_error(Chef::Exceptions::CannotDetermineHomebrewOwner) end diff --git a/spec/unit/mixin/params_validate_spec.rb b/spec/unit/mixin/params_validate_spec.rb index cc2fe198ca..85e1c1abab 100644 --- a/spec/unit/mixin/params_validate_spec.rb +++ b/spec/unit/mixin/params_validate_spec.rb @@ -32,29 +32,29 @@ describe Chef::Mixin::ParamsValidate do end it "should allow a hash and a hash as arguments to validate" do - lambda { @vo.validate({:one => "two"}, {}) }.should_not raise_error + expect { @vo.validate({:one => "two"}, {}) }.not_to raise_error end it "should raise an argument error if validate is called incorrectly" do - lambda { @vo.validate("one", "two") }.should raise_error(ArgumentError) + expect { @vo.validate("one", "two") }.to raise_error(ArgumentError) end it "should require validation map keys to be symbols or strings" do - lambda { @vo.validate({:one => "two"}, { :one => true }) }.should_not raise_error - lambda { @vo.validate({:one => "two"}, { "one" => true }) }.should_not raise_error - lambda { @vo.validate({:one => "two"}, { Hash.new => true }) }.should raise_error(ArgumentError) + expect { @vo.validate({:one => "two"}, { :one => true }) }.not_to raise_error + expect { @vo.validate({:one => "two"}, { "one" => true }) }.not_to raise_error + expect { @vo.validate({:one => "two"}, { Hash.new => true }) }.to raise_error(ArgumentError) end it "should allow options to be required with true" do - lambda { @vo.validate({:one => "two"}, { :one => true }) }.should_not raise_error + expect { @vo.validate({:one => "two"}, { :one => true }) }.not_to raise_error end it "should allow options to be optional with false" do - lambda { @vo.validate({}, {:one => false})}.should_not raise_error + expect { @vo.validate({}, {:one => false})}.not_to raise_error end it "should allow you to check what kind_of? thing an argument is with kind_of" do - lambda { + expect { @vo.validate( {:one => "string"}, { @@ -63,9 +63,9 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error + }.not_to raise_error - lambda { + expect { @vo.validate( {:one => "string"}, { @@ -74,11 +74,11 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should allow you to specify an argument is required with required" do - lambda { + expect { @vo.validate( {:one => "string"}, { @@ -87,9 +87,9 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error + }.not_to raise_error - lambda { + expect { @vo.validate( {:two => "string"}, { @@ -98,9 +98,9 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) - lambda { + expect { @vo.validate( {:two => "string"}, { @@ -109,11 +109,11 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error + }.not_to raise_error end it "should allow you to specify whether an object has a method with respond_to" do - lambda { + expect { @vo.validate( {:one => @vo}, { @@ -122,9 +122,9 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error + }.not_to raise_error - lambda { + expect { @vo.validate( {:one => @vo}, { @@ -133,11 +133,11 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should allow you to specify whether an object has all the given methods with respond_to and an array" do - lambda { + expect { @vo.validate( {:one => @vo}, { @@ -146,9 +146,9 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error + }.not_to raise_error - lambda { + expect { @vo.validate( {:one => @vo}, { @@ -157,7 +157,7 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should let you set a default value with default => value" do @@ -167,11 +167,11 @@ describe Chef::Mixin::ParamsValidate do :default => "is the loneliest number" } }) - arguments[:one].should == "is the loneliest number" + expect(arguments[:one]).to eq("is the loneliest number") end it "should let you check regular expressions" do - lambda { + expect { @vo.validate( { :one => "is good" }, { @@ -180,9 +180,9 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error + }.not_to raise_error - lambda { + expect { @vo.validate( { :one => "is good" }, { @@ -191,11 +191,11 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should let you specify your own callbacks" do - lambda { + expect { @vo.validate( { :one => "is good" }, { @@ -208,9 +208,9 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error + }.not_to raise_error - lambda { + expect { @vo.validate( { :one => "is bad" }, { @@ -223,12 +223,12 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should let you combine checks" do args = { :one => "is good", :two => "is bad" } - lambda { + expect { @vo.validate( args, { @@ -250,9 +250,9 @@ describe Chef::Mixin::ParamsValidate do :three => { :default => "neato mosquito" } } ) - }.should_not raise_error - args[:three].should == "neato mosquito" - lambda { + }.not_to raise_error + expect(args[:three]).to eq("neato mosquito") + expect { @vo.validate( args, { @@ -274,11 +274,11 @@ describe Chef::Mixin::ParamsValidate do :three => { :default => "neato mosquito" } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should raise an ArgumentError if the validation map has an unknown check" do - lambda { @vo.validate( + expect { @vo.validate( { :one => "two" }, { :one => { @@ -286,17 +286,17 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should accept keys that are strings in the options" do - lambda { + expect { @vo.validate({ "one" => "two" }, { :one => { :regex => /^two$/ }}) - }.should_not raise_error + }.not_to raise_error end it "should allow an array to kind_of" do - lambda { + expect { @vo.validate( {:one => "string"}, { @@ -305,8 +305,8 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { @vo.validate( {:one => ["string"]}, { @@ -315,8 +315,8 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should_not raise_error - lambda { + }.not_to raise_error + expect { @vo.validate( {:one => Hash.new}, { @@ -325,48 +325,48 @@ describe Chef::Mixin::ParamsValidate do } } ) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "asserts that a value returns false from a predicate method" do - lambda do + expect do @vo.validate({:not_blank => "should pass"}, {:not_blank => {:cannot_be => :nil, :cannot_be => :empty}}) - end.should_not raise_error - lambda do + end.not_to raise_error + expect do @vo.validate({:not_blank => ""}, {:not_blank => {:cannot_be => :nil, :cannot_be => :empty}}) - end.should raise_error(Chef::Exceptions::ValidationFailed) + end.to raise_error(Chef::Exceptions::ValidationFailed) end it "should set and return a value, then return the same value" do value = "meow" - @vo.set_or_return(:test, value, {}).object_id.should == value.object_id - @vo.set_or_return(:test, nil, {}).object_id.should == value.object_id + expect(@vo.set_or_return(:test, value, {}).object_id).to eq(value.object_id) + expect(@vo.set_or_return(:test, nil, {}).object_id).to eq(value.object_id) end it "should set and return a default value when the argument is nil, then return the same value" do value = "meow" - @vo.set_or_return(:test, nil, { :default => value }).object_id.should == value.object_id - @vo.set_or_return(:test, nil, {}).object_id.should == value.object_id + expect(@vo.set_or_return(:test, nil, { :default => value }).object_id).to eq(value.object_id) + expect(@vo.set_or_return(:test, nil, {}).object_id).to eq(value.object_id) end it "should raise an ArgumentError when argument is nil and required is true" do - lambda { + expect { @vo.set_or_return(:test, nil, { :required => true }) - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should not raise an error when argument is nil and required is false" do - lambda { + expect { @vo.set_or_return(:test, nil, { :required => false }) - }.should_not raise_error + }.not_to raise_error end it "should set and return @name, then return @name for foo when argument is nil" do value = "meow" - @vo.set_or_return(:name, value, { }).object_id.should == value.object_id - @vo.set_or_return(:foo, nil, { :name_attribute => true }).object_id.should == value.object_id + expect(@vo.set_or_return(:name, value, { }).object_id).to eq(value.object_id) + expect(@vo.set_or_return(:foo, nil, { :name_attribute => true }).object_id).to eq(value.object_id) end it "should allow DelayedEvaluator instance to be set for value regardless of restriction" do @@ -377,31 +377,31 @@ describe Chef::Mixin::ParamsValidate do it "should raise an error when delayed evaluated attribute is not valid" do value = Chef::DelayedEvaluator.new{ 'test' } @vo.set_or_return(:test, value, {:kind_of => Numeric}) - lambda do + expect do @vo.set_or_return(:test, nil, {:kind_of => Numeric}) - end.should raise_error(Chef::Exceptions::ValidationFailed) + end.to raise_error(Chef::Exceptions::ValidationFailed) end it "should create DelayedEvaluator instance when #lazy is used" do @vo.set_or_return(:delayed, @vo.lazy{ 'test' }, {}) - @vo.instance_variable_get(:@delayed).should be_a(Chef::DelayedEvaluator) + expect(@vo.instance_variable_get(:@delayed)).to be_a(Chef::DelayedEvaluator) end it "should execute block on each call when DelayedEvaluator" do value = 'fubar' @vo.set_or_return(:test, @vo.lazy{ value }, {}) - @vo.set_or_return(:test, nil, {}).should == 'fubar' + expect(@vo.set_or_return(:test, nil, {})).to eq('fubar') value = 'foobar' - @vo.set_or_return(:test, nil, {}).should == 'foobar' + expect(@vo.set_or_return(:test, nil, {})).to eq('foobar') value = 'fauxbar' - @vo.set_or_return(:test, nil, {}).should == 'fauxbar' + expect(@vo.set_or_return(:test, nil, {})).to eq('fauxbar') end it "should not evaluate non DelayedEvaluator instances" do value = lambda{ 'test' } @vo.set_or_return(:test, value, {}) - @vo.set_or_return(:test, nil, {}).object_id.should == value.object_id - @vo.set_or_return(:test, nil, {}).should be_a(Proc) + expect(@vo.set_or_return(:test, nil, {}).object_id).to eq(value.object_id) + expect(@vo.set_or_return(:test, nil, {})).to be_a(Proc) end end diff --git a/spec/unit/mixin/path_sanity_spec.rb b/spec/unit/mixin/path_sanity_spec.rb index 64c667b483..ec8e182e3d 100644 --- a/spec/unit/mixin/path_sanity_spec.rb +++ b/spec/unit/mixin/path_sanity_spec.rb @@ -33,54 +33,54 @@ describe Chef::Mixin::PathSanity do Chef::Config[:enforce_path_sanity] = true @ruby_bindir = '/some/ruby/bin' @gem_bindir = '/some/gem/bin' - Gem.stub(:bindir).and_return(@gem_bindir) - RbConfig::CONFIG.stub(:[]).with('bindir').and_return(@ruby_bindir) - Chef::Platform.stub(:windows?).and_return(false) + allow(Gem).to receive(:bindir).and_return(@gem_bindir) + allow(RbConfig::CONFIG).to receive(:[]).with('bindir').and_return(@ruby_bindir) + allow(Chef::Platform).to receive(:windows?).and_return(false) end it "adds all useful PATHs even if environment is an empty hash" do env={} @sanity.enforce_path_sanity(env) - env["PATH"].should == "#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + expect(env["PATH"]).to eq("#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end it "adds all useful PATHs that are not yet in PATH to PATH" do env = {"PATH" => ""} @sanity.enforce_path_sanity(env) - env["PATH"].should == "#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + expect(env["PATH"]).to eq("#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end it "does not re-add paths that already exist in PATH" do env = {"PATH" => "/usr/bin:/sbin:/bin"} @sanity.enforce_path_sanity(env) - env["PATH"].should == "/usr/bin:/sbin:/bin:#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin" + expect(env["PATH"]).to eq("/usr/bin:/sbin:/bin:#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin") end it "adds the current executing Ruby's bindir and Gem bindir to the PATH" do env = {"PATH" => ""} @sanity.enforce_path_sanity(env) - env["PATH"].should == "#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + expect(env["PATH"]).to eq("#{@ruby_bindir}:#{@gem_bindir}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end it "does not create entries for Ruby/Gem bindirs if they exist in SANE_PATH or PATH" do ruby_bindir = '/usr/bin' gem_bindir = '/yo/gabba/gabba' - Gem.stub(:bindir).and_return(gem_bindir) - RbConfig::CONFIG.stub(:[]).with('bindir').and_return(ruby_bindir) + allow(Gem).to receive(:bindir).and_return(gem_bindir) + allow(RbConfig::CONFIG).to receive(:[]).with('bindir').and_return(ruby_bindir) env = {"PATH" => gem_bindir} @sanity.enforce_path_sanity(env) - env["PATH"].should == "/yo/gabba/gabba:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + expect(env["PATH"]).to eq("/yo/gabba/gabba:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") end it "builds a valid windows path" do ruby_bindir = 'C:\ruby\bin' gem_bindir = 'C:\gems\bin' - Gem.stub(:bindir).and_return(gem_bindir) - RbConfig::CONFIG.stub(:[]).with('bindir').and_return(ruby_bindir) - Chef::Platform.stub(:windows?).and_return(true) + allow(Gem).to receive(:bindir).and_return(gem_bindir) + allow(RbConfig::CONFIG).to receive(:[]).with('bindir').and_return(ruby_bindir) + allow(Chef::Platform).to receive(:windows?).and_return(true) env = {"PATH" => 'C:\Windows\system32;C:\mr\softie'} @sanity.enforce_path_sanity(env) - env["PATH"].should == "C:\\Windows\\system32;C:\\mr\\softie;#{ruby_bindir};#{gem_bindir}" + expect(env["PATH"]).to eq("C:\\Windows\\system32;C:\\mr\\softie;#{ruby_bindir};#{gem_bindir}") end end end diff --git a/spec/unit/mixin/securable_spec.rb b/spec/unit/mixin/securable_spec.rb index 10954083d8..714d6dedae 100644 --- a/spec/unit/mixin/securable_spec.rb +++ b/spec/unit/mixin/securable_spec.rb @@ -28,19 +28,19 @@ describe Chef::Mixin::Securable do end it "should accept a group name or id for group" do - lambda { @securable.group "root" }.should_not raise_error - lambda { @securable.group 123 }.should_not raise_error - lambda { @securable.group "+bad:group" }.should raise_error(ArgumentError) + expect { @securable.group "root" }.not_to raise_error + expect { @securable.group 123 }.not_to raise_error + expect { @securable.group "+bad:group" }.to raise_error(ArgumentError) end it "should accept a user name or id for owner" do - lambda { @securable.owner "root" }.should_not raise_error - lambda { @securable.owner 123 }.should_not raise_error - lambda { @securable.owner "+bad:owner" }.should raise_error(ArgumentError) + expect { @securable.owner "root" }.not_to raise_error + expect { @securable.owner 123 }.not_to raise_error + expect { @securable.owner "+bad:owner" }.to raise_error(ArgumentError) end it "allows the owner to be specified as #user" do - @securable.should respond_to(:user) + expect(@securable).to respond_to(:user) end describe "unix-specific behavior" do @@ -54,69 +54,69 @@ describe Chef::Mixin::Securable do end it "should accept group/owner names with spaces and backslashes" do - lambda { @securable.group 'test\ group' }.should_not raise_error - lambda { @securable.owner 'test\ group' }.should_not raise_error + expect { @securable.group 'test\ group' }.not_to raise_error + expect { @securable.owner 'test\ group' }.not_to raise_error end it "should accept group/owner names that are a single character or digit" do - lambda { @securable.group 'v' }.should_not raise_error - lambda { @securable.group '1' }.should_not raise_error - lambda { @securable.owner 'v' }.should_not raise_error - lambda { @securable.owner '1' }.should_not raise_error + expect { @securable.group 'v' }.not_to raise_error + expect { @securable.group '1' }.not_to raise_error + expect { @securable.owner 'v' }.not_to raise_error + expect { @securable.owner '1' }.not_to raise_error end it "should not accept group/owner names starting with '-', '+', or '~'" do - lambda { @securable.group '-test' }.should raise_error(ArgumentError) - lambda { @securable.group '+test' }.should raise_error(ArgumentError) - lambda { @securable.group '~test' }.should raise_error(ArgumentError) - lambda { @securable.group 'te-st' }.should_not raise_error - lambda { @securable.group 'te+st' }.should_not raise_error - lambda { @securable.group 'te~st' }.should_not raise_error - lambda { @securable.owner '-test' }.should raise_error(ArgumentError) - lambda { @securable.owner '+test' }.should raise_error(ArgumentError) - lambda { @securable.owner '~test' }.should raise_error(ArgumentError) - lambda { @securable.owner 'te-st' }.should_not raise_error - lambda { @securable.owner 'te+st' }.should_not raise_error - lambda { @securable.owner 'te~st' }.should_not raise_error + expect { @securable.group '-test' }.to raise_error(ArgumentError) + expect { @securable.group '+test' }.to raise_error(ArgumentError) + expect { @securable.group '~test' }.to raise_error(ArgumentError) + expect { @securable.group 'te-st' }.not_to raise_error + expect { @securable.group 'te+st' }.not_to raise_error + expect { @securable.group 'te~st' }.not_to raise_error + expect { @securable.owner '-test' }.to raise_error(ArgumentError) + expect { @securable.owner '+test' }.to raise_error(ArgumentError) + expect { @securable.owner '~test' }.to raise_error(ArgumentError) + expect { @securable.owner 'te-st' }.not_to raise_error + expect { @securable.owner 'te+st' }.not_to raise_error + expect { @securable.owner 'te~st' }.not_to raise_error end it "should not accept group/owner names containing ':', ',' or non-space whitespace" do - lambda { @securable.group ':test' }.should raise_error(ArgumentError) - lambda { @securable.group 'te:st' }.should raise_error(ArgumentError) - lambda { @securable.group ',test' }.should raise_error(ArgumentError) - lambda { @securable.group 'te,st' }.should raise_error(ArgumentError) - lambda { @securable.group "\ttest" }.should raise_error(ArgumentError) - lambda { @securable.group "te\tst" }.should raise_error(ArgumentError) - lambda { @securable.group "\rtest" }.should raise_error(ArgumentError) - lambda { @securable.group "te\rst" }.should raise_error(ArgumentError) - lambda { @securable.group "\ftest" }.should raise_error(ArgumentError) - lambda { @securable.group "te\fst" }.should raise_error(ArgumentError) - lambda { @securable.group "\0test" }.should raise_error(ArgumentError) - lambda { @securable.group "te\0st" }.should raise_error(ArgumentError) - lambda { @securable.owner ':test' }.should raise_error(ArgumentError) - lambda { @securable.owner 'te:st' }.should raise_error(ArgumentError) - lambda { @securable.owner ',test' }.should raise_error(ArgumentError) - lambda { @securable.owner 'te,st' }.should raise_error(ArgumentError) - lambda { @securable.owner "\ttest" }.should raise_error(ArgumentError) - lambda { @securable.owner "te\tst" }.should raise_error(ArgumentError) - lambda { @securable.owner "\rtest" }.should raise_error(ArgumentError) - lambda { @securable.owner "te\rst" }.should raise_error(ArgumentError) - lambda { @securable.owner "\ftest" }.should raise_error(ArgumentError) - lambda { @securable.owner "te\fst" }.should raise_error(ArgumentError) - lambda { @securable.owner "\0test" }.should raise_error(ArgumentError) - lambda { @securable.owner "te\0st" }.should raise_error(ArgumentError) + expect { @securable.group ':test' }.to raise_error(ArgumentError) + expect { @securable.group 'te:st' }.to raise_error(ArgumentError) + expect { @securable.group ',test' }.to raise_error(ArgumentError) + expect { @securable.group 'te,st' }.to raise_error(ArgumentError) + expect { @securable.group "\ttest" }.to raise_error(ArgumentError) + expect { @securable.group "te\tst" }.to raise_error(ArgumentError) + expect { @securable.group "\rtest" }.to raise_error(ArgumentError) + expect { @securable.group "te\rst" }.to raise_error(ArgumentError) + expect { @securable.group "\ftest" }.to raise_error(ArgumentError) + expect { @securable.group "te\fst" }.to raise_error(ArgumentError) + expect { @securable.group "\0test" }.to raise_error(ArgumentError) + expect { @securable.group "te\0st" }.to raise_error(ArgumentError) + expect { @securable.owner ':test' }.to raise_error(ArgumentError) + expect { @securable.owner 'te:st' }.to raise_error(ArgumentError) + expect { @securable.owner ',test' }.to raise_error(ArgumentError) + expect { @securable.owner 'te,st' }.to raise_error(ArgumentError) + expect { @securable.owner "\ttest" }.to raise_error(ArgumentError) + expect { @securable.owner "te\tst" }.to raise_error(ArgumentError) + expect { @securable.owner "\rtest" }.to raise_error(ArgumentError) + expect { @securable.owner "te\rst" }.to raise_error(ArgumentError) + expect { @securable.owner "\ftest" }.to raise_error(ArgumentError) + expect { @securable.owner "te\fst" }.to raise_error(ArgumentError) + expect { @securable.owner "\0test" }.to raise_error(ArgumentError) + expect { @securable.owner "te\0st" }.to raise_error(ArgumentError) end it "should accept Active Directory-style domain names pulled in via LDAP (on unix hosts)" do - lambda { @securable.owner "domain\@user" }.should_not raise_error - lambda { @securable.owner "domain\\user" }.should_not raise_error - lambda { @securable.group "domain\@group" }.should_not raise_error - lambda { @securable.group "domain\\group" }.should_not raise_error - lambda { @securable.group "domain\\group^name" }.should_not raise_error + expect { @securable.owner "domain\@user" }.not_to raise_error + expect { @securable.owner "domain\\user" }.not_to raise_error + expect { @securable.group "domain\@group" }.not_to raise_error + expect { @securable.group "domain\\group" }.not_to raise_error + expect { @securable.group "domain\\group^name" }.not_to raise_error end it "should not accept group/owner names containing embedded carriage returns" do - pending "XXX: params_validate needs to be extended to support multi-line regex" + skip "XXX: params_validate needs to be extended to support multi-line regex" #lambda { @securable.group "\ntest" }.should raise_error(ArgumentError) #lambda { @securable.group "te\nst" }.should raise_error(ArgumentError) #lambda { @securable.owner "\ntest" }.should raise_error(ArgumentError) @@ -124,53 +124,53 @@ describe Chef::Mixin::Securable do end it "should accept group/owner names in UTF-8" do - lambda { @securable.group 'tëst' }.should_not raise_error - lambda { @securable.group 'ë' }.should_not raise_error - lambda { @securable.owner 'tëst' }.should_not raise_error - lambda { @securable.owner 'ë' }.should_not raise_error + expect { @securable.group 'tëst' }.not_to raise_error + expect { @securable.group 'ë' }.not_to raise_error + expect { @securable.owner 'tëst' }.not_to raise_error + expect { @securable.owner 'ë' }.not_to raise_error end it "should accept a unix file mode in string form as an octal number" do - lambda { @securable.mode "0" }.should_not raise_error - lambda { @securable.mode "0000" }.should_not raise_error - lambda { @securable.mode "0111" }.should_not raise_error - lambda { @securable.mode "0444" }.should_not raise_error - - lambda { @securable.mode "111" }.should_not raise_error - lambda { @securable.mode "444" }.should_not raise_error - lambda { @securable.mode "7777" }.should_not raise_error - lambda { @securable.mode "07777" }.should_not raise_error - - lambda { @securable.mode "-01" }.should raise_error(ArgumentError) - lambda { @securable.mode "010000" }.should raise_error(ArgumentError) - lambda { @securable.mode "-1" }.should raise_error(ArgumentError) - lambda { @securable.mode "10000" }.should raise_error(ArgumentError) - - lambda { @securable.mode "07778" }.should raise_error(ArgumentError) - lambda { @securable.mode "7778" }.should raise_error(ArgumentError) - lambda { @securable.mode "4095" }.should raise_error(ArgumentError) - - lambda { @securable.mode "0foo1234" }.should raise_error(ArgumentError) - lambda { @securable.mode "foo1234" }.should raise_error(ArgumentError) + expect { @securable.mode "0" }.not_to raise_error + expect { @securable.mode "0000" }.not_to raise_error + expect { @securable.mode "0111" }.not_to raise_error + expect { @securable.mode "0444" }.not_to raise_error + + expect { @securable.mode "111" }.not_to raise_error + expect { @securable.mode "444" }.not_to raise_error + expect { @securable.mode "7777" }.not_to raise_error + expect { @securable.mode "07777" }.not_to raise_error + + expect { @securable.mode "-01" }.to raise_error(ArgumentError) + expect { @securable.mode "010000" }.to raise_error(ArgumentError) + expect { @securable.mode "-1" }.to raise_error(ArgumentError) + expect { @securable.mode "10000" }.to raise_error(ArgumentError) + + expect { @securable.mode "07778" }.to raise_error(ArgumentError) + expect { @securable.mode "7778" }.to raise_error(ArgumentError) + expect { @securable.mode "4095" }.to raise_error(ArgumentError) + + expect { @securable.mode "0foo1234" }.to raise_error(ArgumentError) + expect { @securable.mode "foo1234" }.to raise_error(ArgumentError) end it "should accept a unix file mode in numeric form as a ruby-interpreted integer" do - lambda { @securable.mode(0) }.should_not raise_error - lambda { @securable.mode(0000) }.should_not raise_error - lambda { @securable.mode(444) }.should_not raise_error - lambda { @securable.mode(0444) }.should_not raise_error - lambda { @securable.mode(07777) }.should_not raise_error - - lambda { @securable.mode(292) }.should_not raise_error - lambda { @securable.mode(4095) }.should_not raise_error - - lambda { @securable.mode(0111) }.should_not raise_error - lambda { @securable.mode(73) }.should_not raise_error - - lambda { @securable.mode(-01) }.should raise_error(ArgumentError) - lambda { @securable.mode(010000) }.should raise_error(ArgumentError) - lambda { @securable.mode(-1) }.should raise_error(ArgumentError) - lambda { @securable.mode(4096) }.should raise_error(ArgumentError) + expect { @securable.mode(0) }.not_to raise_error + expect { @securable.mode(0000) }.not_to raise_error + expect { @securable.mode(444) }.not_to raise_error + expect { @securable.mode(0444) }.not_to raise_error + expect { @securable.mode(07777) }.not_to raise_error + + expect { @securable.mode(292) }.not_to raise_error + expect { @securable.mode(4095) }.not_to raise_error + + expect { @securable.mode(0111) }.not_to raise_error + expect { @securable.mode(73) }.not_to raise_error + + expect { @securable.mode(-01) }.to raise_error(ArgumentError) + expect { @securable.mode(010000) }.to raise_error(ArgumentError) + expect { @securable.mode(-1) }.to raise_error(ArgumentError) + expect { @securable.mode(4096) }.to raise_error(ArgumentError) end end @@ -187,94 +187,94 @@ describe Chef::Mixin::Securable do end it "should not accept a group name or id for group with spaces and multiple backslashes" do - lambda { @securable.group 'test\ \group' }.should raise_error(ArgumentError) + expect { @securable.group 'test\ \group' }.to raise_error(ArgumentError) end it "should accept a unix file mode in string form as an octal number" do - lambda { @securable.mode "0" }.should_not raise_error - lambda { @securable.mode "0000" }.should_not raise_error - lambda { @securable.mode "0111" }.should_not raise_error - lambda { @securable.mode "0444" }.should_not raise_error - - lambda { @securable.mode "111" }.should_not raise_error - lambda { @securable.mode "444" }.should_not raise_error - lambda { @securable.mode "7777" }.should raise_error(ArgumentError) - lambda { @securable.mode "07777" }.should raise_error(ArgumentError) - - lambda { @securable.mode "-01" }.should raise_error(ArgumentError) - lambda { @securable.mode "010000" }.should raise_error(ArgumentError) - lambda { @securable.mode "-1" }.should raise_error(ArgumentError) - lambda { @securable.mode "10000" }.should raise_error(ArgumentError) - - lambda { @securable.mode "07778" }.should raise_error(ArgumentError) - lambda { @securable.mode "7778" }.should raise_error(ArgumentError) - lambda { @securable.mode "4095" }.should raise_error(ArgumentError) - - lambda { @securable.mode "0foo1234" }.should raise_error(ArgumentError) - lambda { @securable.mode "foo1234" }.should raise_error(ArgumentError) + expect { @securable.mode "0" }.not_to raise_error + expect { @securable.mode "0000" }.not_to raise_error + expect { @securable.mode "0111" }.not_to raise_error + expect { @securable.mode "0444" }.not_to raise_error + + expect { @securable.mode "111" }.not_to raise_error + expect { @securable.mode "444" }.not_to raise_error + expect { @securable.mode "7777" }.to raise_error(ArgumentError) + expect { @securable.mode "07777" }.to raise_error(ArgumentError) + + expect { @securable.mode "-01" }.to raise_error(ArgumentError) + expect { @securable.mode "010000" }.to raise_error(ArgumentError) + expect { @securable.mode "-1" }.to raise_error(ArgumentError) + expect { @securable.mode "10000" }.to raise_error(ArgumentError) + + expect { @securable.mode "07778" }.to raise_error(ArgumentError) + expect { @securable.mode "7778" }.to raise_error(ArgumentError) + expect { @securable.mode "4095" }.to raise_error(ArgumentError) + + expect { @securable.mode "0foo1234" }.to raise_error(ArgumentError) + expect { @securable.mode "foo1234" }.to raise_error(ArgumentError) end it "should accept a unix file mode in numeric form as a ruby-interpreted integer" do - lambda { @securable.mode 0 }.should_not raise_error - lambda { @securable.mode 0000 }.should_not raise_error - lambda { @securable.mode 444 }.should_not raise_error - lambda { @securable.mode 0444 }.should_not raise_error - lambda { @securable.mode 07777 }.should raise_error(ArgumentError) - - lambda { @securable.mode 292 }.should_not raise_error - lambda { @securable.mode 4095 }.should raise_error(ArgumentError) - - lambda { @securable.mode 0111 }.should_not raise_error - lambda { @securable.mode 73 }.should_not raise_error - - lambda { @securable.mode -01 }.should raise_error(ArgumentError) - lambda { @securable.mode 010000 }.should raise_error(ArgumentError) - lambda { @securable.mode -1 }.should raise_error(ArgumentError) - lambda { @securable.mode 4096 }.should raise_error(ArgumentError) + expect { @securable.mode 0 }.not_to raise_error + expect { @securable.mode 0000 }.not_to raise_error + expect { @securable.mode 444 }.not_to raise_error + expect { @securable.mode 0444 }.not_to raise_error + expect { @securable.mode 07777 }.to raise_error(ArgumentError) + + expect { @securable.mode 292 }.not_to raise_error + expect { @securable.mode 4095 }.to raise_error(ArgumentError) + + expect { @securable.mode 0111 }.not_to raise_error + expect { @securable.mode 73 }.not_to raise_error + + expect { @securable.mode -01 }.to raise_error(ArgumentError) + expect { @securable.mode 010000 }.to raise_error(ArgumentError) + expect { @securable.mode -1 }.to raise_error(ArgumentError) + expect { @securable.mode 4096 }.to raise_error(ArgumentError) end it "should allow you to specify :full_control, :modify, :read_execute, :read, and :write rights" do - lambda { @securable.rights :full_control, "The Dude" }.should_not raise_error - lambda { @securable.rights :modify, "The Dude" }.should_not raise_error - lambda { @securable.rights :read_execute, "The Dude" }.should_not raise_error - lambda { @securable.rights :read, "The Dude" }.should_not raise_error - lambda { @securable.rights :write, "The Dude" }.should_not raise_error - lambda { @securable.rights :to_party, "The Dude" }.should raise_error(ArgumentError) + expect { @securable.rights :full_control, "The Dude" }.not_to raise_error + expect { @securable.rights :modify, "The Dude" }.not_to raise_error + expect { @securable.rights :read_execute, "The Dude" }.not_to raise_error + expect { @securable.rights :read, "The Dude" }.not_to raise_error + expect { @securable.rights :write, "The Dude" }.not_to raise_error + expect { @securable.rights :to_party, "The Dude" }.to raise_error(ArgumentError) end it "should allow you to specify :full_control, :modify, :read_execute, :read, and :write deny_rights" do - lambda { @securable.deny_rights :full_control, "The Dude" }.should_not raise_error - lambda { @securable.deny_rights :modify, "The Dude" }.should_not raise_error - lambda { @securable.deny_rights :read_execute, "The Dude" }.should_not raise_error - lambda { @securable.deny_rights :read, "The Dude" }.should_not raise_error - lambda { @securable.deny_rights :write, "The Dude" }.should_not raise_error - lambda { @securable.deny_rights :to_party, "The Dude" }.should raise_error(ArgumentError) + expect { @securable.deny_rights :full_control, "The Dude" }.not_to raise_error + expect { @securable.deny_rights :modify, "The Dude" }.not_to raise_error + expect { @securable.deny_rights :read_execute, "The Dude" }.not_to raise_error + expect { @securable.deny_rights :read, "The Dude" }.not_to raise_error + expect { @securable.deny_rights :write, "The Dude" }.not_to raise_error + expect { @securable.deny_rights :to_party, "The Dude" }.to raise_error(ArgumentError) end it "should accept a principal as a string or an array" do - lambda { @securable.rights :read, "The Dude" }.should_not raise_error - lambda { @securable.rights :read, ["The Dude","Donny"] }.should_not raise_error - lambda { @securable.rights :read, 3 }.should raise_error(ArgumentError) + expect { @securable.rights :read, "The Dude" }.not_to raise_error + expect { @securable.rights :read, ["The Dude","Donny"] }.not_to raise_error + expect { @securable.rights :read, 3 }.to raise_error(ArgumentError) end it "should allow you to specify whether the permissions applies_to_children with true/false/:containers_only/:objects_only" do - lambda { @securable.rights :read, "The Dude", :applies_to_children => false }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => :containers_only }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => :objects_only }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => 'poop' }.should raise_error(ArgumentError) + expect { @securable.rights :read, "The Dude", :applies_to_children => false }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => :containers_only }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => :objects_only }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => 'poop' }.to raise_error(ArgumentError) end it "should allow you to specify whether the permissions applies_to_self with true/false" do - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_self => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_self => 'poop' }.should raise_error(ArgumentError) + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_self => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_self => 'poop' }.to raise_error(ArgumentError) end it "should allow you to specify whether the permissions applies one_level_deep with true/false" do - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => 'poop' }.should raise_error(ArgumentError) + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => 'poop' }.to raise_error(ArgumentError) end it "should allow multiple rights and deny_rights declarations" do @@ -283,32 +283,32 @@ describe Chef::Mixin::Securable do @securable.rights :full_control, "The Dude" @securable.rights :write, "The Dude" @securable.deny_rights :read, "The Dude" - @securable.rights.size.should == 3 - @securable.deny_rights.size.should == 2 + expect(@securable.rights.size).to eq(3) + expect(@securable.deny_rights.size).to eq(2) end it "should allow you to specify whether the permission applies_to_self only if you specified applies_to_children" do - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => false }.should raise_error(ArgumentError) - lambda { @securable.rights :read, "The Dude", :applies_to_self => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_self => false }.should_not raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => false }.to raise_error(ArgumentError) + expect { @securable.rights :read, "The Dude", :applies_to_self => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_self => false }.not_to raise_error end it "should allow you to specify whether the permission applies one_level_deep only if you specified applies_to_children" do - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => true }.should raise_error(ArgumentError) - lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => false }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :one_level_deep => true }.should_not raise_error - lambda { @securable.rights :read, "The Dude", :one_level_deep => false }.should_not raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.not_to raise_error + expect { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => true }.to raise_error(ArgumentError) + expect { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => false }.not_to raise_error + expect { @securable.rights :read, "The Dude", :one_level_deep => true }.not_to raise_error + expect { @securable.rights :read, "The Dude", :one_level_deep => false }.not_to raise_error end it "should allow you to specify whether the permissions inherit with true/false" do - lambda { @securable.inherits true }.should_not raise_error - lambda { @securable.inherits false }.should_not raise_error - lambda { @securable.inherits "monkey" }.should raise_error(ArgumentError) + expect { @securable.inherits true }.not_to raise_error + expect { @securable.inherits false }.not_to raise_error + expect { @securable.inherits "monkey" }.to raise_error(ArgumentError) end end end diff --git a/spec/unit/mixin/shell_out_spec.rb b/spec/unit/mixin/shell_out_spec.rb index 38a63a32ee..afce4dc826 100644 --- a/spec/unit/mixin/shell_out_spec.rb +++ b/spec/unit/mixin/shell_out_spec.rb @@ -38,7 +38,7 @@ describe Chef::Mixin::ShellOut do let(:command_args) { [ cmd ] } it 'should not edit command args' do - should eql(command_args) + is_expected.to eql(command_args) end end @@ -47,7 +47,7 @@ describe Chef::Mixin::ShellOut do let(:environment) { { 'LC_ALL' => 'C' } } it 'should not edit command args' do - should eql(command_args) + is_expected.to eql(command_args) end end @@ -66,7 +66,7 @@ describe Chef::Mixin::ShellOut do let(:command_log_level) { :warn } it 'should convert :command_log_level to :log_level' do - should eql [ cmd, { :log_level => command_log_level } ] + is_expected.to eql [ cmd, { :log_level => command_log_level } ] end should_emit_deprecation_warning_about :command_log_level, :log_level @@ -77,7 +77,7 @@ describe Chef::Mixin::ShellOut do let(:command_log_prepend) { 'PROVIDER:' } it 'should convert :command_log_prepend to :log_tag' do - should eql [ cmd, { :log_tag => command_log_prepend } ] + is_expected.to eql [ cmd, { :log_tag => command_log_prepend } ] end should_emit_deprecation_warning_about :command_log_prepend, :log_tag @@ -88,7 +88,7 @@ describe Chef::Mixin::ShellOut do let(:command_log_level) { :warn } it "should convert 'command_log_level' to :log_level" do - should eql [ cmd, { :log_level => command_log_level } ] + is_expected.to eql [ cmd, { :log_level => command_log_level } ] end should_emit_deprecation_warning_about :command_log_level, :log_level @@ -99,7 +99,7 @@ describe Chef::Mixin::ShellOut do let(:command_log_prepend) { 'PROVIDER:' } it "should convert 'command_log_prepend' to :log_tag" do - should eql [ cmd, { :log_tag => command_log_prepend } ] + is_expected.to eql [ cmd, { :log_tag => command_log_prepend } ] end should_emit_deprecation_warning_about :command_log_prepend, :log_tag diff --git a/spec/unit/mixin/template_spec.rb b/spec/unit/mixin/template_spec.rb index 63fa81782e..f02bd34b8f 100644 --- a/spec/unit/mixin/template_spec.rb +++ b/spec/unit/mixin/template_spec.rb @@ -30,7 +30,7 @@ describe Chef::Mixin::Template, "render_template" do it "should render the template evaluated in the given context" do @context[:foo] = "bar" output = @context.render_template_from_string("<%= @foo %>") - output.should == "bar" + expect(output).to eq("bar") end template_contents = [ "Fancy\r\nTemplate\r\n\r\n", @@ -39,14 +39,14 @@ describe Chef::Mixin::Template, "render_template" do describe "when running on windows" do before do - Chef::Platform.stub(:windows?).and_return(true) + allow(Chef::Platform).to receive(:windows?).and_return(true) end it "should render the templates with windows line endings" do template_contents.each do |template_content| output = @context.render_template_from_string(template_content) output.each_line do |line| - line.should end_with("\r\n") + expect(line).to end_with("\r\n") end end end @@ -54,14 +54,14 @@ describe Chef::Mixin::Template, "render_template" do describe "when running on unix" do before do - Chef::Platform.stub(:windows?).and_return(false) + allow(Chef::Platform).to receive(:windows?).and_return(false) end it "should render the templates with unix line endings" do template_contents.each do |template_content| output = @context.render_template_from_string(template_content) output.each_line do |line| - line.should end_with("\n") + expect(line).to end_with("\n") end end end @@ -70,7 +70,7 @@ describe Chef::Mixin::Template, "render_template" do it "should provide a node method to access @node" do @context[:node] = "tehShizzle" output = @context.render_template_from_string("<%= @node %>") - output.should == "tehShizzle" + expect(output).to eq("tehShizzle") end describe "with a template resource" do @@ -100,7 +100,7 @@ describe Chef::Mixin::Template, "render_template" do it "should provide a render method" do output = @template_context.render_template_from_string("before {<%= render('test.erb').strip -%>} after") - output.should == "before {We could be diving for pearls!} after" + expect(output).to eq("before {We could be diving for pearls!} after") end it "should render local files" do @@ -110,7 +110,7 @@ describe Chef::Mixin::Template, "render_template" do tf.rewind output = @template_context.render_template_from_string("before {<%= render '#{tf.path}', :local => true %>} after") - output.should == "before {test} after" + expect(output).to eq("before {test} after") ensure tf.close end @@ -120,7 +120,7 @@ describe Chef::Mixin::Template, "render_template" do @template_context[:template_finder] = Chef::Provider::TemplateFinder.new(@run_context, 'apache2', @node) output = @template_context.render_template_from_string("before {<%= render('test.erb', :cookbook => 'openldap').strip %>} after") - output.should == "before {We could be diving for pearls!} after" + expect(output).to eq("before {We could be diving for pearls!} after") end it "should render using the source argument if provided" do @@ -130,7 +130,7 @@ describe Chef::Mixin::Template, "render_template" do tf.rewind output = @template_context.render_template_from_string("before {<%= render 'something', :local => true, :source => '#{tf.path}' %>} after") - output.should == "before {test} after" + expect(output).to eq("before {test} after") ensure tf.close end @@ -140,7 +140,7 @@ describe Chef::Mixin::Template, "render_template" do @node.normal[:slappiness] = "happiness" output = @template_context.render_template_from_string("before {<%= render 'openldap_stuff.conf.erb' %>} after") - output.should == "before {slappiness is happiness} after" + expect(output).to eq("before {slappiness is happiness} after") end it "should pass the original variables to partials" do @@ -152,29 +152,29 @@ describe Chef::Mixin::Template, "render_template" do it "should pass variables to partials" do output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb', :variables => {:secret => 'whatever' } %>} after") - output.should == "before {super secret is whatever} after" + expect(output).to eq("before {super secret is whatever} after") end it "should pass variables to partials even if they are named the same" do @template_context[:secret] = 'one' output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb', :variables => {:secret => 'two' } %>} after <%= @secret %>") - output.should == "before {super secret is two} after one" + expect(output).to eq("before {super secret is two} after one") end it "should pass nil for missing variables in partials" do output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb', :variables => {} %>} after") - output.should == "before {super secret is } after" + expect(output).to eq("before {super secret is } after") output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb' %>} after") - output.should == "before {super secret is } after" + expect(output).to eq("before {super secret is } after") end it "should render nested partials" do path = File.expand_path(File.join(CHEF_SPEC_DATA, "partial_one.erb")) output = @template_context.render_template_from_string("before {<%= render('#{path}', :local => true).strip %>} after") - output.should == "before {partial one We could be diving for pearls! calling home} after" + expect(output).to eq("before {partial one We could be diving for pearls! calling home} after") end describe "when customizing the template context" do @@ -187,7 +187,7 @@ describe Chef::Mixin::Template, "render_template" do end @template_context._extend_modules([mod]) output = @template_context.render_template_from_string("<%=hello%>") - output.should == "ohai" + expect(output).to eq("ohai") end it "emits a warning when overriding 'core' methods" do @@ -202,7 +202,7 @@ describe Chef::Mixin::Template, "render_template" do end end ['node', 'render', 'render_template', 'render_template_from_string'].each do |method_name| - Chef::Log.should_receive(:warn).with(/^Core template method `#{method_name}' overridden by extension module/) + expect(Chef::Log).to receive(:warn).with(/^Core template method `#{method_name}' overridden by extension module/) end @template_context._extend_modules([mod]) end @@ -216,11 +216,11 @@ describe Chef::Mixin::Template, "render_template" do end it "should catch and re-raise the exception as a TemplateError" do - lambda { do_raise }.should raise_error(Chef::Mixin::Template::TemplateError) + expect { do_raise }.to raise_error(Chef::Mixin::Template::TemplateError) end it "should raise an error if an attempt is made to access node but it is nil" do - lambda {@context.render_template_from_string("<%= node %>") {|r| r}}.should raise_error(Chef::Mixin::Template::TemplateError) + expect {@context.render_template_from_string("<%= node %>") {|r| r}}.to raise_error(Chef::Mixin::Template::TemplateError) end describe "the raised TemplateError" do @@ -233,35 +233,35 @@ describe Chef::Mixin::Template, "render_template" do end it "should have the original exception" do - @exception.original_exception.should be - @exception.original_exception.message.should =~ /undefined local variable or method `this_is_not_defined'/ + expect(@exception.original_exception).to be + expect(@exception.original_exception.message).to match(/undefined local variable or method `this_is_not_defined'/) end it "should determine the line number of the exception" do - @exception.line_number.should == 4 + expect(@exception.line_number).to eq(4) end it "should provide a source listing of the template around the exception" do - @exception.source_listing.should == " 2: bar\n 3: baz\n 4: <%= this_is_not_defined %>\n 5: quin\n 6: qunx" + expect(@exception.source_listing).to eq(" 2: bar\n 3: baz\n 4: <%= this_is_not_defined %>\n 5: quin\n 6: qunx") end it "should provide the evaluation context of the template" do - @exception.context.should == @context + expect(@exception.context).to eq(@context) end it "should defer the message to the original exception" do - @exception.message.should =~ /undefined local variable or method `this_is_not_defined'/ + expect(@exception.message).to match(/undefined local variable or method `this_is_not_defined'/) end it "should provide a nice source location" do - @exception.source_location.should == "on line #4" + expect(@exception.source_location).to eq("on line #4") end it "should create a pretty output for the terminal" do - @exception.to_s.should =~ /Chef::Mixin::Template::TemplateError/ - @exception.to_s.should =~ /undefined local variable or method `this_is_not_defined'/ - @exception.to_s.should include(" 2: bar\n 3: baz\n 4: <%= this_is_not_defined %>\n 5: quin\n 6: qunx") - @exception.to_s.should include(@exception.original_exception.backtrace.first) + expect(@exception.to_s).to match(/Chef::Mixin::Template::TemplateError/) + expect(@exception.to_s).to match(/undefined local variable or method `this_is_not_defined'/) + expect(@exception.to_s).to include(" 2: bar\n 3: baz\n 4: <%= this_is_not_defined %>\n 5: quin\n 6: qunx") + expect(@exception.to_s).to include(@exception.original_exception.backtrace.first) end end end diff --git a/spec/unit/mixin/windows_architecture_helper_spec.rb b/spec/unit/mixin/windows_architecture_helper_spec.rb index f59602d716..3803d69371 100644 --- a/spec/unit/mixin/windows_architecture_helper_spec.rb +++ b/spec/unit/mixin/windows_architecture_helper_spec.rb @@ -35,13 +35,13 @@ describe Chef::Mixin::WindowsArchitectureHelper do it "returns true when valid architectures are passed to valid_windows_architecture?" do @valid_architectures.each do | architecture | - valid_windows_architecture?(architecture).should == true + expect(valid_windows_architecture?(architecture)).to eq(true) end end it "returns false when invalid architectures are passed to valid_windows_architecture?" do @invalid_architectures.each do | architecture | - valid_windows_architecture?(architecture).should == false + expect(valid_windows_architecture?(architecture)).to eq(false) end end @@ -54,7 +54,7 @@ describe Chef::Mixin::WindowsArchitectureHelper do it "raises an error if an invalid architecture is passed to assert_valid_windows_architecture!" do @invalid_architectures.each do | architecture | begin - assert_valid_windows_architecture!(architecture).should raise_error Chef::Exceptions::Win32ArchitectureIncorrect + expect(assert_valid_windows_architecture!(architecture)).to raise_error Chef::Exceptions::Win32ArchitectureIncorrect rescue Chef::Exceptions::Win32ArchitectureIncorrect end end @@ -75,8 +75,8 @@ describe Chef::Mixin::WindowsArchitectureHelper do new_node.default["kernel"][:machine] = node_architecture.to_s @valid_architectures.each do | supported_architecture | - node_supports_windows_architecture?(new_node, supported_architecture).should == true if only_valid_combinations && (supported_architecture != :x86_64 && node_architecture != :i386 ) - node_supports_windows_architecture?(new_node, supported_architecture).should == false if ! only_valid_combinations && (supported_architecture == :x86_64 && node_architecture == :i386 ) + expect(node_supports_windows_architecture?(new_node, supported_architecture)).to eq(true) if only_valid_combinations && (supported_architecture != :x86_64 && node_architecture != :i386 ) + expect(node_supports_windows_architecture?(new_node, supported_architecture)).to eq(false) if ! only_valid_combinations && (supported_architecture == :x86_64 && node_architecture == :i386 ) end end end diff --git a/spec/unit/mixin/xml_escape_spec.rb b/spec/unit/mixin/xml_escape_spec.rb index 83debb5907..c5156cfb7b 100644 --- a/spec/unit/mixin/xml_escape_spec.rb +++ b/spec/unit/mixin/xml_escape_spec.rb @@ -28,27 +28,27 @@ describe Chef::Mixin::XMLEscape do end it "escapes ampersands to '&'" do - @escaper.xml_escape("&").should == "&" + expect(@escaper.xml_escape("&")).to eq("&") end it "escapes angle brackets to < or >" do - @escaper.xml_escape("<").should == "<" - @escaper.xml_escape(">").should == ">" + expect(@escaper.xml_escape("<")).to eq("<") + expect(@escaper.xml_escape(">")).to eq(">") end it "does not modify ASCII strings" do - @escaper.xml_escape('foobarbaz!@#$%^*()').should == 'foobarbaz!@#$%^*()' + expect(@escaper.xml_escape('foobarbaz!@#$%^*()')).to eq('foobarbaz!@#$%^*()') end it "converts invalid bytes to asterisks" do - @escaper.xml_escape("\x00").should == "*" + expect(@escaper.xml_escape("\x00")).to eq("*") end it "converts UTF-8 correctly" do - @escaper.xml_escape("\xC2\xA9").should == '©' + expect(@escaper.xml_escape("\xC2\xA9")).to eq('©') end it "converts win 1252 characters correctly" do - @escaper.xml_escape("\x80").should == '€' + expect(@escaper.xml_escape("\x80")).to eq('€') end end diff --git a/spec/unit/monkey_patches/string_spec.rb b/spec/unit/monkey_patches/string_spec.rb index 8c6710b38e..74e3753229 100644 --- a/spec/unit/monkey_patches/string_spec.rb +++ b/spec/unit/monkey_patches/string_spec.rb @@ -27,8 +27,8 @@ describe String do ch = num.chr ch.force_encoding('ASCII-8BIT') if ch.respond_to? :force_encoding - ch.ord.should be_a_kind_of(Fixnum) - ch.ord.should == num + expect(ch.ord).to be_a_kind_of(Fixnum) + expect(ch.ord).to eq(num) end end diff --git a/spec/unit/monkey_patches/uri_spec.rb b/spec/unit/monkey_patches/uri_spec.rb index cff252ac3b..9aca1fc9f1 100644 --- a/spec/unit/monkey_patches/uri_spec.rb +++ b/spec/unit/monkey_patches/uri_spec.rb @@ -26,7 +26,7 @@ describe URI do end it "returns the hostname without brackets" do - ipv6_uri.hostname.should == "2a00:1450:4009:809::1008" + expect(ipv6_uri.hostname).to eq("2a00:1450:4009:809::1008") end end diff --git a/spec/unit/monologger_spec.rb b/spec/unit/monologger_spec.rb index 3babc29218..8689ea0aaa 100644 --- a/spec/unit/monologger_spec.rb +++ b/spec/unit/monologger_spec.rb @@ -23,14 +23,14 @@ describe MonoLogger do it "should disable buffering when passed an IO stream" do STDOUT.sync = false MonoLogger.new(STDOUT) - STDOUT.sync.should == true + expect(STDOUT.sync).to eq(true) end describe "when given an object that responds to write and close e.g. IO" do it "should use the object directly" do stream = StringIO.new MonoLogger.new(stream).fatal("Houston, we've had a problem.") - stream.string.should =~ /Houston, we've had a problem./ + expect(stream.string).to match(/Houston, we've had a problem./) end end @@ -39,7 +39,7 @@ describe MonoLogger do temp_file = Tempfile.new("rspec-monologger-log") temp_file.close MonoLogger.new(temp_file.path).fatal("Do, or do not. There is no try.") - File.read(temp_file.path).should =~ /Do, or do not. There is no try./ + expect(File.read(temp_file.path)).to match(/Do, or do not. There is no try./) end end end diff --git a/spec/unit/node/attribute_spec.rb b/spec/unit/node/attribute_spec.rb index 5325117d6c..c5d0f2398e 100644 --- a/spec/unit/node/attribute_spec.rb +++ b/spec/unit/node/attribute_spec.rb @@ -215,22 +215,22 @@ describe Chef::Node::Attribute do describe "initialize" do it "should return a Chef::Node::Attribute" do - @attributes.should be_a_kind_of(Chef::Node::Attribute) + expect(@attributes).to be_a_kind_of(Chef::Node::Attribute) end it "should take an Automatioc, Normal, Default and Override hash" do - lambda { Chef::Node::Attribute.new({}, {}, {}, {}) }.should_not raise_error + expect { Chef::Node::Attribute.new({}, {}, {}, {}) }.not_to raise_error end [ :normal, :default, :override, :automatic ].each do |accessor| it "should set #{accessor}" do na = Chef::Node::Attribute.new({ :normal => true }, { :default => true }, { :override => true }, { :automatic => true }) - na.send(accessor).should == { accessor.to_s => true } + expect(na.send(accessor)).to eq({ accessor.to_s => true }) end end it "should be enumerable" do - @attributes.should be_is_a(Enumerable) + expect(@attributes).to be_is_a(Enumerable) end end @@ -242,7 +242,7 @@ describe Chef::Node::Attribute do # the "strict" conversion method that should only be implemented by # things that are truly Array-like, so NoMethodError is the right choice. # (cf. there is no Hash#to_ary). - lambda { @attributes.default.to_ary }.should raise_error(NoMethodError) + expect { @attributes.default.to_ary }.to raise_error(NoMethodError) end end @@ -274,7 +274,7 @@ describe Chef::Node::Attribute do ["force_override", "force_override"], ["automatic", "automatic"] ] - @attributes.debug_value(:foo, :bar).should == expected + expect(@attributes.debug_value(:foo, :bar)).to eq(expected) end end @@ -288,68 +288,68 @@ describe Chef::Node::Attribute do @attributes.default!["default"] = "force default" @attributes.role_default["default"] = "role default" @attributes.env_default["default"] = "environment default" - @attributes["default"].should == "force default" + expect(@attributes["default"]).to eq("force default") end it "prefers role_default over environment or cookbook default" do @attributes.role_default["default"] = "role default" @attributes.env_default["default"] = "environment default" - @attributes["default"].should == "role default" + expect(@attributes["default"]).to eq("role default") end it "prefers environment default over cookbook default" do @attributes.env_default["default"] = "environment default" - @attributes["default"].should == "environment default" + expect(@attributes["default"]).to eq("environment default") end it "returns the cookbook default when no other default values are present" do - @attributes["default"].should == "cookbook default" + expect(@attributes["default"]).to eq("cookbook default") end it "prefers 'forced overrides' over role or cookbook overrides" do @attributes.override!["override"] = "force override" @attributes.env_override["override"] = "environment override" @attributes.role_override["override"] = "role override" - @attributes["override"].should == "force override" + expect(@attributes["override"]).to eq("force override") end it "prefers environment overrides over role or cookbook overrides" do @attributes.env_override["override"] = "environment override" @attributes.role_override["override"] = "role override" - @attributes["override"].should == "environment override" + expect(@attributes["override"]).to eq("environment override") end it "prefers role overrides over cookbook overrides" do @attributes.role_override["override"] = "role override" - @attributes["override"].should == "role override" + expect(@attributes["override"]).to eq("role override") end it "returns cookbook overrides when no other overrides are present" do - @attributes["override"].should == "cookbook override" + expect(@attributes["override"]).to eq("cookbook override") end it "merges arrays within the default precedence" do @attributes.role_default["array"] = %w{role} @attributes.env_default["array"] = %w{env} - @attributes["array"].should == %w{env role} + expect(@attributes["array"]).to eq(%w{env role}) end it "merges arrays within the override precedence" do @attributes.role_override["array"] = %w{role} @attributes.env_override["array"] = %w{env} - @attributes["array"].should == %w{role env} + expect(@attributes["array"]).to eq(%w{role env}) end it "does not merge arrays between default and normal" do @attributes.role_default["array"] = %w{role} @attributes.normal["array"] = %w{normal} - @attributes["array"].should == %w{normal} + expect(@attributes["array"]).to eq(%w{normal}) end it "does not merge arrays between normal and override" do @attributes.normal["array"] = %w{normal} @attributes.role_override["array"] = %w{role} - @attributes["array"].should == %w{role} + expect(@attributes["array"]).to eq(%w{role}) end it "merges nested hashes between precedence levels" do @@ -358,9 +358,9 @@ describe Chef::Node::Attribute do @attributes.normal = {"a" => {"b" => {"normal" => "normal"}}} @attributes.override = {"a" => {"override" => "role"}} @attributes.automatic = {"a" => {"automatic" => "auto"}} - @attributes["a"].should == {"b"=>{"default"=>"default", "normal"=>"normal"}, + expect(@attributes["a"]).to eq({"b"=>{"default"=>"default", "normal"=>"normal"}, "override"=>"role", - "automatic"=>"auto"} + "automatic"=>"auto"}) end end @@ -377,94 +377,94 @@ describe Chef::Node::Attribute do end it "merges all types of overrides into a combined override" do - @attributes.combined_override["co"].should == "cookbook override" - @attributes.combined_override["ro"].should == "role override" - @attributes.combined_override["eo"].should == "env override" - @attributes.combined_override["fo"].should == "force override" + expect(@attributes.combined_override["co"]).to eq("cookbook override") + expect(@attributes.combined_override["ro"]).to eq("role override") + expect(@attributes.combined_override["eo"]).to eq("env override") + expect(@attributes.combined_override["fo"]).to eq("force override") end it "merges all types of defaults into a combined default" do - @attributes.combined_default["cd"].should == "cookbook default" - @attributes.combined_default["rd"].should == "role default" - @attributes.combined_default["ed"].should == "env default" - @attributes.combined_default["fd"].should == "force default" + expect(@attributes.combined_default["cd"]).to eq("cookbook default") + expect(@attributes.combined_default["rd"]).to eq("role default") + expect(@attributes.combined_default["ed"]).to eq("env default") + expect(@attributes.combined_default["fd"]).to eq("force default") end end describe "[]" do it "should return override data if it exists" do - @attributes["macaddress"].should == "00:00:00:00:00:00" + expect(@attributes["macaddress"]).to eq("00:00:00:00:00:00") end it "should return attribute data if it is not overridden" do - @attributes["platform"].should == "mac_os_x" + expect(@attributes["platform"]).to eq("mac_os_x") end it "should return data that doesn't have corresponding keys in every hash" do - @attributes["command"]["ps"].should == "ps -ef" + expect(@attributes["command"]["ps"]).to eq("ps -ef") end it "should return default data if it is not overriden or in attribute data" do - @attributes["music"]["mastodon"].should == "rocks" + expect(@attributes["music"]["mastodon"]).to eq("rocks") end it "should prefer the override data over an available default" do - @attributes["music"]["mars_volta"].should == "cicatriz" + expect(@attributes["music"]["mars_volta"]).to eq("cicatriz") end it "should prefer the attribute data over an available default" do - @attributes["music"]["jimmy_eat_world"].should == "nice" + expect(@attributes["music"]["jimmy_eat_world"]).to eq("nice") end it "should prefer override data over default data if there is no attribute data" do - @attributes["hot"]["day"].should == "sunday" + expect(@attributes["hot"]["day"]).to eq("sunday") end it "should return the merged hash if all three have values" do result = @attributes["music"] - result["mars_volta"].should == "cicatriz" - result["jimmy_eat_world"].should == "nice" - result["mastodon"].should == "rocks" + expect(result["mars_volta"]).to eq("cicatriz") + expect(result["jimmy_eat_world"]).to eq("nice") + expect(result["mastodon"]).to eq("rocks") end end describe "[]=" do it "should error out when the type of attribute to set has not been specified" do @attributes.normal["the_ghost"] = { } - lambda { @attributes["the_ghost"]["exterminate"] = false }.should raise_error(Chef::Exceptions::ImmutableAttributeModification) + expect { @attributes["the_ghost"]["exterminate"] = false }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end it "should let you set an attribute value when another hash has an intermediate value" do @attributes.normal["the_ghost"] = { "exterminate" => "the future" } - lambda { @attributes.normal["the_ghost"]["eviscerate"]["tomorrow"] = false }.should_not raise_error + expect { @attributes.normal["the_ghost"]["eviscerate"]["tomorrow"] = false }.not_to raise_error end it "should set the attribute value" do @attributes.normal["longboard"] = "surfing" - @attributes.normal["longboard"].should == "surfing" - @attributes.normal["longboard"].should == "surfing" + expect(@attributes.normal["longboard"]).to eq("surfing") + expect(@attributes.normal["longboard"]).to eq("surfing") end it "should set deeply nested attribute values when a precedence level is specified" do @attributes.normal["deftones"]["hunters"]["nap"] = "surfing" - @attributes.normal["deftones"]["hunters"]["nap"].should == "surfing" + expect(@attributes.normal["deftones"]["hunters"]["nap"]).to eq("surfing") end it "should die if you try and do nested attributes that do not exist without read vivification" do - lambda { @attributes["foo"]["bar"] = :baz }.should raise_error + expect { @attributes["foo"]["bar"] = :baz }.to raise_error end it "should let you set attributes manually without vivification" do @attributes.normal["foo"] = Mash.new @attributes.normal["foo"]["bar"] = :baz - @attributes.normal["foo"]["bar"].should == :baz + expect(@attributes.normal["foo"]["bar"]).to eq(:baz) end it "should optionally skip setting the value if one already exists" do @attributes.set_unless_value_present = true @attributes.normal["hostname"] = "bar" - @attributes["hostname"].should == "latte" + expect(@attributes["hostname"]).to eq("latte") end it "does not support ||= when setting" do @@ -472,19 +472,19 @@ describe Chef::Node::Attribute do # Users who need this behavior can use set_unless and friends @attributes.normal["foo"] = Mash.new @attributes.normal["foo"]["bar"] ||= "stop the world" - @attributes.normal["foo"]["bar"].should == {} + expect(@attributes.normal["foo"]["bar"]).to eq({}) end end describe "to_hash" do it "should convert to a hash" do - @attributes.to_hash.class.should == Hash + expect(@attributes.to_hash.class).to eq(Hash) end it "should convert to a hash based on current state" do hash = @attributes["hot"].to_hash - hash.class.should == Hash - hash["day"].should == "sunday" + expect(hash.class).to eq(Hash) + expect(hash["day"]).to eq("sunday") end end @@ -497,65 +497,65 @@ describe Chef::Node::Attribute do describe "has_key?" do it "should return true if an attribute exists" do - @attributes.has_key?("music").should == true + expect(@attributes.has_key?("music")).to eq(true) end it "should return false if an attribute does not exist" do - @attributes.has_key?("ninja").should == false + expect(@attributes.has_key?("ninja")).to eq(false) end it "should return false if an attribute does not exist using dot notation" do - @attributes.has_key?("does_not_exist_at_all").should == false + expect(@attributes.has_key?("does_not_exist_at_all")).to eq(false) end it "should return true if an attribute exists but is set to nil using dot notation" do - @attributes.music.deeper.has_key?("gates_of_ishtar").should == true + expect(@attributes.music.deeper.has_key?("gates_of_ishtar")).to eq(true) end it "should return true if an attribute exists but is set to false" do @attributes.has_key?("music") - @attributes["music"].has_key?("apophis").should == true + expect(@attributes["music"].has_key?("apophis")).to eq(true) end it "does not find keys above the current nesting level" do - @attributes["music"]["this"]["apparatus"].should_not have_key("this") + expect(@attributes["music"]["this"]["apparatus"]).not_to have_key("this") end it "does not find keys below the current nesting level" do - @attributes["music"]["this"].should_not have_key("must") + expect(@attributes["music"]["this"]).not_to have_key("must") end [:include?, :key?, :member?].each do |method| it "should alias the method #{method} to itself" do - @attributes.should respond_to(method) + expect(@attributes).to respond_to(method) end it "#{method} should behave like has_key?" do - @attributes.send(method, "music").should == true + expect(@attributes.send(method, "music")).to eq(true) end end end describe "attribute?" do it "should return true if an attribute exists" do - @attributes.attribute?("music").should == true + expect(@attributes.attribute?("music")).to eq(true) end it "should return false if an attribute does not exist" do - @attributes.attribute?("ninja").should == false + expect(@attributes.attribute?("ninja")).to eq(false) end end describe "method_missing" do it "should behave like a [] lookup" do - @attributes.music.mastodon.should == "rocks" + expect(@attributes.music.mastodon).to eq("rocks") end it "should allow the last method to set a value if it has an = sign on the end" do @attributes.normal.music.mastodon = [ "dream", "still", "shining" ] @attributes.reset - @attributes.normal.music.mastodon.should == [ "dream", "still", "shining" ] + expect(@attributes.normal.music.mastodon).to eq([ "dream", "still", "shining" ]) end end @@ -584,12 +584,12 @@ describe Chef::Node::Attribute do @attributes.keys.each do |k| collect << k end - collect.include?("one").should == true - collect.include?("hut").should == true - collect.include?("snakes").should == true - collect.include?("snack").should == true - collect.include?("place").should == true - collect.length.should == 5 + expect(collect.include?("one")).to eq(true) + expect(collect.include?("hut")).to eq(true) + expect(collect.include?("snakes")).to eq(true) + expect(collect.include?("snack")).to eq(true) + expect(collect.include?("place")).to eq(true) + expect(collect.length).to eq(5) end it "should yield lower if we go deeper" do @@ -597,14 +597,14 @@ describe Chef::Node::Attribute do @attributes.one.keys.each do |k| collect << k end - collect.include?("two").should == true - collect.include?("four").should == true - collect.include?("six").should == true - collect.length.should == 3 + expect(collect.include?("two")).to eq(true) + expect(collect.include?("four")).to eq(true) + expect(collect.include?("six")).to eq(true) + expect(collect.length).to eq(3) end it "should not raise an exception if one of the hashes has a nil value on a deep lookup" do - lambda { @attributes.place.keys { |k| } }.should_not raise_error + expect { @attributes.place.keys { |k| } }.not_to raise_error end end @@ -633,15 +633,15 @@ describe Chef::Node::Attribute do collect[k] = v end - collect["one"].should == "six" - collect["hut"].should == "three" - collect["snakes"].should == "on a plane" - collect["snack"].should == "cookies" + expect(collect["one"]).to eq("six") + expect(collect["hut"]).to eq("three") + expect(collect["snakes"]).to eq("on a plane") + expect(collect["snack"]).to eq("cookies") end it "should yield as a two-element array" do @attributes.each do |a| - a.should be_an_instance_of(Array) + expect(a).to be_an_instance_of(Array) end end end @@ -666,7 +666,7 @@ describe Chef::Node::Attribute do end it "should respond to each_key" do - @attributes.should respond_to(:each_key) + expect(@attributes).to respond_to(:each_key) end it "should yield each top level key, post merge rules" do @@ -675,10 +675,10 @@ describe Chef::Node::Attribute do collect << k end - collect.should include("one") - collect.should include("snack") - collect.should include("hut") - collect.should include("snakes") + expect(collect).to include("one") + expect(collect).to include("snack") + expect(collect).to include("hut") + expect(collect).to include("snakes") end end @@ -702,7 +702,7 @@ describe Chef::Node::Attribute do end it "should respond to each_pair" do - @attributes.should respond_to(:each_pair) + expect(@attributes).to respond_to(:each_pair) end it "should yield each top level key and value pair, post merge rules" do @@ -711,10 +711,10 @@ describe Chef::Node::Attribute do collect[k] = v end - collect["one"].should == "six" - collect["hut"].should == "three" - collect["snakes"].should == "on a plane" - collect["snack"].should == "cookies" + expect(collect["one"]).to eq("six") + expect(collect["hut"]).to eq("three") + expect(collect["snakes"]).to eq("on a plane") + expect(collect["snack"]).to eq("cookies") end end @@ -738,7 +738,7 @@ describe Chef::Node::Attribute do end it "should respond to each_value" do - @attributes.should respond_to(:each_value) + expect(@attributes).to respond_to(:each_value) end it "should yield each value, post merge rules" do @@ -747,9 +747,9 @@ describe Chef::Node::Attribute do collect << v end - collect.should include("cookies") - collect.should include("three") - collect.should include("on a plane") + expect(collect).to include("cookies") + expect(collect).to include("three") + expect(collect).to include("on a plane") end it "should yield four elements" do @@ -758,7 +758,7 @@ describe Chef::Node::Attribute do collect << v end - collect.length.should == 4 + expect(collect.length).to eq(4) end end @@ -783,15 +783,15 @@ describe Chef::Node::Attribute do end it "should respond to empty?" do - @attributes.should respond_to(:empty?) + expect(@attributes).to respond_to(:empty?) end it "should return true when there are no keys" do - @empty.empty?.should == true + expect(@empty.empty?).to eq(true) end it "should return false when there are keys" do - @attributes.empty?.should == false + expect(@attributes.empty?).to eq(false) end end @@ -816,7 +816,7 @@ describe Chef::Node::Attribute do end it "should respond to fetch" do - @attributes.should respond_to(:fetch) + expect(@attributes).to respond_to(:fetch) end describe "when the key exists" do @@ -827,7 +827,7 @@ describe Chef::Node::Attribute do "snakes" => "on a plane", "snack" => "cookies" }.each do |k,v| - @attributes.fetch(k).should == v + expect(@attributes.fetch(k)).to eq(v) end end end @@ -835,19 +835,19 @@ describe Chef::Node::Attribute do describe "when the key does not exist" do describe "and no args are passed" do it "should raise an indexerror" do - lambda { @attributes.fetch("lololol") }.should raise_error(IndexError) + expect { @attributes.fetch("lololol") }.to raise_error(IndexError) end end describe "and a default arg is passed" do it "should return the value of the default arg" do - @attributes.fetch("lol", "blah").should == "blah" + expect(@attributes.fetch("lol", "blah")).to eq("blah") end end describe "and a block is passed" do it "should run the block and return its value" do - @attributes.fetch("lol") { |x| "#{x}, blah" }.should == "lol, blah" + expect(@attributes.fetch("lol") { |x| "#{x}, blah" }).to eq("lol, blah") end end end @@ -873,19 +873,19 @@ describe Chef::Node::Attribute do end it "should respond to has_value?" do - @attributes.should respond_to(:has_value?) + expect(@attributes).to respond_to(:has_value?) end it "should return true if any key has the value supplied" do - @attributes.has_value?("cookies").should == true + expect(@attributes.has_value?("cookies")).to eq(true) end it "should return false no key has the value supplied" do - @attributes.has_value?("lololol").should == false + expect(@attributes.has_value?("lololol")).to eq(false) end it "should alias value?" do - @attributes.should respond_to(:value?) + expect(@attributes).to respond_to(:value?) end end @@ -918,13 +918,13 @@ describe Chef::Node::Attribute do end it "should respond to index" do - @attributes.should respond_to(:index) + expect(@attributes).to respond_to(:index) end describe "when the value is indexed" do it "should return the index" do silence do - @attributes.index("six").should == "one" + expect(@attributes.index("six")).to eq("one") end end end @@ -932,7 +932,7 @@ describe Chef::Node::Attribute do describe "when the value is not indexed" do it "should return nil" do silence do - @attributes.index("lolol").should == nil + expect(@attributes.index("lolol")).to eq(nil) end end end @@ -960,18 +960,18 @@ describe Chef::Node::Attribute do end it "should respond to values" do - @attributes.should respond_to(:values) + expect(@attributes).to respond_to(:values) end it "should return an array of values" do - @attributes.values.length.should == 4 + expect(@attributes.values.length).to eq(4) end it "should match the values output from each" do - @attributes.values.should include("six") - @attributes.values.should include("cookies") - @attributes.values.should include("three") - @attributes.values.should include("on a plane") + expect(@attributes.values).to include("six") + expect(@attributes.values).to include("cookies") + expect(@attributes.values).to include("three") + expect(@attributes.values).to include("on a plane") end end @@ -996,26 +996,26 @@ describe Chef::Node::Attribute do end it "should respond to select" do - @attributes.should respond_to(:select) + expect(@attributes).to respond_to(:select) end if RUBY_VERSION >= "1.8.7" it "should not raise a LocalJumpError if no block is given" do - lambda { @attributes.select }.should_not raise_error + expect { @attributes.select }.not_to raise_error end else it "should raise a LocalJumpError if no block is given" do - lambda{ @attributes.select }.should raise_error(LocalJumpError) + expect{ @attributes.select }.to raise_error(LocalJumpError) end end it "should return an empty hash/array (ruby-version-dependent) for a block containing nil" do - @attributes.select { nil }.should == {}.select { nil } + expect(@attributes.select { nil }).to eq({}.select { nil }) end # sorted for spec clarity it "should return a new array of k,v pairs for which the block returns true" do - @attributes.select { true }.sort.should == ( + expect(@attributes.select { true }.sort).to eq( [ ["hut", "three"], ["one", "six"], @@ -1048,37 +1048,37 @@ describe Chef::Node::Attribute do end it "should respond to size" do - @attributes.should respond_to(:size) + expect(@attributes).to respond_to(:size) end it "should alias length to size" do - @attributes.should respond_to(:length) + expect(@attributes).to respond_to(:length) end it "should return 0 for an empty attribute" do - @empty.size.should == 0 + expect(@empty.size).to eq(0) end it "should return the number of pairs" do - @attributes.size.should == 4 + expect(@attributes.size).to eq(4) end end describe "kind_of?" do it "should falsely inform you that it is a Hash" do - @attributes.should be_a_kind_of(Hash) + expect(@attributes).to be_a_kind_of(Hash) end it "should falsely inform you that it is a Mash" do - @attributes.should be_a_kind_of(Mash) + expect(@attributes).to be_a_kind_of(Mash) end it "should inform you that it is a Chef::Node::Attribute" do - @attributes.should be_a_kind_of(Chef::Node::Attribute) + expect(@attributes).to be_a_kind_of(Chef::Node::Attribute) end it "should inform you that it is anything else" do - @attributes.should_not be_a_kind_of(Chef::Node) + expect(@attributes).not_to be_a_kind_of(Chef::Node) end end @@ -1087,8 +1087,8 @@ describe Chef::Node::Attribute do # NOTE: previous implementation hid the values, showing @automatic={...} # That is nice and compact, but hides a lot of info, which seems counter # to the point of calling #inspect... - @attributes.inspect.should =~ /@automatic=\{.*\}/ - @attributes.inspect.should =~ /@normal=\{.*\}/ + expect(@attributes.inspect).to match(/@automatic=\{.*\}/) + expect(@attributes.inspect).to match(/@normal=\{.*\}/) end end @@ -1099,13 +1099,13 @@ describe Chef::Node::Attribute do :shift ].each do |mutator| it "resets the cache when the mutator #{mutator} is called" do - @attributes.should_receive(:reset_cache) + expect(@attributes).to receive(:reset_cache) @attributes.default.send(mutator) end end it "resets the cache when the mutator delete is called" do - @attributes.should_receive(:reset_cache) + expect(@attributes).to receive(:reset_cache) @attributes.default.delete(:music) end @@ -1116,7 +1116,7 @@ describe Chef::Node::Attribute do ].each do |mutator| it "resets the cache when the mutator #{mutator} is called" do # Implementation of Mash means that this could get called many times. That's okay. - @attributes.should_receive(:reset_cache).at_least(1).times + expect(@attributes).to receive(:reset_cache).at_least(1).times @attributes.default.send(mutator, {:foo => :bar}) end end @@ -1129,7 +1129,7 @@ describe Chef::Node::Attribute do ].each do |mutator| it "resets the cache when the mutator #{mutator} is called" do # Implementation of Mash means that this could get called many times. That's okay. - @attributes.should_receive(:reset_cache).at_least(1).times + expect(@attributes).to receive(:reset_cache).at_least(1).times block = lambda {|k,v| true } @attributes.default.send(mutator, &block) end @@ -1142,7 +1142,7 @@ describe Chef::Node::Attribute do @attributes.default[:foo][:bar] = "set on original" subtree = @attributes[:foo] @attributes.default[:foo].dup[:bar] = "set on dup" - subtree[:bar].should == "set on original" + expect(subtree[:bar]).to eq("set on original") end end @@ -1151,35 +1151,35 @@ describe Chef::Node::Attribute do it "converts the input in to a VividMash tree (default)" do @attributes.default = {} @attributes.default.foo = "bar" - @attributes.merged_attributes[:foo].should == "bar" + expect(@attributes.merged_attributes[:foo]).to eq("bar") end it "converts the input in to a VividMash tree (normal)" do @attributes.normal = {} @attributes.normal.foo = "bar" - @attributes.merged_attributes[:foo].should == "bar" + expect(@attributes.merged_attributes[:foo]).to eq("bar") end it "converts the input in to a VividMash tree (override)" do @attributes.override = {} @attributes.override.foo = "bar" - @attributes.merged_attributes[:foo].should == "bar" + expect(@attributes.merged_attributes[:foo]).to eq("bar") end it "converts the input in to a VividMash tree (automatic)" do @attributes.automatic = {} @attributes.automatic.foo = "bar" - @attributes.merged_attributes[:foo].should == "bar" + expect(@attributes.merged_attributes[:foo]).to eq("bar") end end describe "when attemping to write without specifying precedence" do it "raises an error when using []=" do - lambda { @attributes[:new_key] = "new value" }.should raise_error(Chef::Exceptions::ImmutableAttributeModification) + expect { @attributes[:new_key] = "new value" }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end it "raises an error when using `attr=value`" do - lambda { @attributes.new_key = "new value" }.should raise_error(Chef::Exceptions::ImmutableAttributeModification) + expect { @attributes.new_key = "new value" }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end end diff --git a/spec/unit/node/immutable_collections_spec.rb b/spec/unit/node/immutable_collections_spec.rb index 1c216e327a..b1e7b9169b 100644 --- a/spec/unit/node/immutable_collections_spec.rb +++ b/spec/unit/node/immutable_collections_spec.rb @@ -30,28 +30,28 @@ describe Chef::Node::ImmutableMash do end it "element references like regular hash" do - @immutable_mash[:top][:second_level].should == "some value" + expect(@immutable_mash[:top][:second_level]).to eq("some value") end it "elelment references like a regular Mash" do - @immutable_mash[:top_level_2].should == %w[array of values] + expect(@immutable_mash[:top_level_2]).to eq(%w[array of values]) end it "converts Hash-like inputs into ImmutableMash's" do - @immutable_mash[:top].should be_a(Chef::Node::ImmutableMash) + expect(@immutable_mash[:top]).to be_a(Chef::Node::ImmutableMash) end it "converts array inputs into ImmutableArray's" do - @immutable_mash[:top_level_2].should be_a(Chef::Node::ImmutableArray) + expect(@immutable_mash[:top_level_2]).to be_a(Chef::Node::ImmutableArray) end it "converts arrays of hashes to ImmutableArray's of ImmutableMashes" do - @immutable_mash[:top_level_3].first.should be_a(Chef::Node::ImmutableMash) + expect(@immutable_mash[:top_level_3].first).to be_a(Chef::Node::ImmutableMash) end it "converts nested hashes to ImmutableMashes" do - @immutable_mash[:top_level_4].should be_a(Chef::Node::ImmutableMash) - @immutable_mash[:top_level_4][:level2].should be_a(Chef::Node::ImmutableMash) + expect(@immutable_mash[:top_level_4]).to be_a(Chef::Node::ImmutableMash) + expect(@immutable_mash[:top_level_4][:level2]).to be_a(Chef::Node::ImmutableMash) end describe "to_hash" do @@ -60,23 +60,23 @@ describe Chef::Node::ImmutableMash do end it "converts an immutable mash to a new mutable hash" do - @copy.should be_instance_of(Hash) + expect(@copy).to be_instance_of(Hash) end it "converts an immutable nested mash to a new mutable hash" do - @copy['top_level_4']['level2'].should be_instance_of(Hash) + expect(@copy['top_level_4']['level2']).to be_instance_of(Hash) end it "converts an immutable nested array to a new mutable array" do - @copy['top_level_2'].should be_instance_of(Array) + expect(@copy['top_level_2']).to be_instance_of(Array) end it "should create a mash with the same content" do - @copy.should == @immutable_mash + expect(@copy).to eq(@immutable_mash) end it 'should allow mutation' do - lambda { @copy['m'] = 'm' }.should_not raise_error + expect { @copy['m'] = 'm' }.not_to raise_error end end @@ -97,14 +97,14 @@ describe Chef::Node::ImmutableMash do :shift ].each do |mutator| it "doesn't allow mutation via `#{mutator}'" do - lambda { @immutable_mash.send(mutator) }.should raise_error + expect { @immutable_mash.send(mutator) }.to raise_error end end it "returns a mutable version of itself when duped" do mutable = @immutable_mash.dup mutable[:new_key] = :value - mutable[:new_key].should == :value + expect(mutable[:new_key]).to eq(:value) end end @@ -154,7 +154,7 @@ describe Chef::Node::ImmutableArray do :unshift ].each do |mutator| it "does not allow mutation via `#{mutator}" do - lambda { @immutable_array.send(mutator)}.should raise_error + expect { @immutable_array.send(mutator)}.to raise_error end end @@ -165,7 +165,7 @@ describe Chef::Node::ImmutableArray do it "returns a mutable version of itself when duped" do mutable = @immutable_array.dup mutable[0] = :value - mutable[0].should == :value + expect(mutable[0]).to eq(:value) end describe "to_a" do @@ -174,23 +174,23 @@ describe Chef::Node::ImmutableArray do end it "converts an immutable array to a new mutable array" do - @copy.should be_instance_of(Array) + expect(@copy).to be_instance_of(Array) end it "converts an immutable nested array to a new mutable array" do - @copy[1].should be_instance_of(Array) + expect(@copy[1]).to be_instance_of(Array) end it "converts an immutable nested mash to a new mutable hash" do - @copy[2].should be_instance_of(Hash) + expect(@copy[2]).to be_instance_of(Hash) end it "should create an array with the same content" do - @copy.should == @immutable_nested_array + expect(@copy).to eq(@immutable_nested_array) end it 'should allow mutation' do - lambda { @copy << 'm' }.should_not raise_error + expect { @copy << 'm' }.not_to raise_error end end diff --git a/spec/unit/node_spec.rb b/spec/unit/node_spec.rb index da7a67aec1..24209d367f 100644 --- a/spec/unit/node_spec.rb +++ b/spec/unit/node_spec.rb @@ -28,167 +28,167 @@ describe Chef::Node do it "creates a node and assigns it a name" do node = Chef::Node.build('solo-node') - node.name.should == 'solo-node' + expect(node.name).to eq('solo-node') end it "should validate the name of the node" do - lambda{Chef::Node.build('solo node')}.should raise_error(Chef::Exceptions::ValidationFailed) + expect{Chef::Node.build('solo node')}.to raise_error(Chef::Exceptions::ValidationFailed) end it "should be sortable" do n1 = Chef::Node.build('alpha') n2 = Chef::Node.build('beta') n3 = Chef::Node.build('omega') - [n3, n1, n2].sort.should == [n1, n2, n3] + expect([n3, n1, n2].sort).to eq([n1, n2, n3]) end describe "when the node does not exist on the server" do before do response = OpenStruct.new(:code => '404') exception = Net::HTTPServerException.new("404 not found", response) - Chef::Node.stub(:load).and_raise(exception) + allow(Chef::Node).to receive(:load).and_raise(exception) node.name("created-node") end it "creates a new node for find_or_create" do - Chef::Node.stub(:new).and_return(node) - node.should_receive(:create).and_return(node) + allow(Chef::Node).to receive(:new).and_return(node) + expect(node).to receive(:create).and_return(node) node = Chef::Node.find_or_create("created-node") - node.name.should == 'created-node' - node.should equal(node) + expect(node.name).to eq('created-node') + expect(node).to equal(node) end end describe "when the node exists on the server" do before do node.name('existing-node') - Chef::Node.stub(:load).and_return(node) + allow(Chef::Node).to receive(:load).and_return(node) end it "loads the node via the REST API for find_or_create" do - Chef::Node.find_or_create('existing-node').should equal(node) + expect(Chef::Node.find_or_create('existing-node')).to equal(node) end end describe "run_state" do it "is an empty hash" do - node.run_state.should respond_to(:keys) - node.run_state.should be_empty + expect(node.run_state).to respond_to(:keys) + expect(node.run_state).to be_empty end end describe "initialize" do it "should default to the '_default' chef_environment" do n = Chef::Node.new - n.chef_environment.should == '_default' + expect(n.chef_environment).to eq('_default') end end describe "name" do it "should allow you to set a name with name(something)" do - lambda { node.name("latte") }.should_not raise_error + expect { node.name("latte") }.not_to raise_error end it "should return the name with name()" do node.name("latte") - node.name.should eql("latte") + expect(node.name).to eql("latte") end it "should always have a string for name" do - lambda { node.name(Hash.new) }.should raise_error(ArgumentError) + expect { node.name(Hash.new) }.to raise_error(ArgumentError) end it "cannot be blank" do - lambda { node.name("")}.should raise_error(Chef::Exceptions::ValidationFailed) + expect { node.name("")}.to raise_error(Chef::Exceptions::ValidationFailed) end it "should not accept name doesn't match /^[\-[:alnum:]_:.]+$/" do - lambda { node.name("space in it")}.should raise_error(Chef::Exceptions::ValidationFailed) + expect { node.name("space in it")}.to raise_error(Chef::Exceptions::ValidationFailed) end end describe "chef_environment" do it "should set an environment with chef_environment(something)" do - lambda { node.chef_environment("latte") }.should_not raise_error + expect { node.chef_environment("latte") }.not_to raise_error end it "should return the chef_environment with chef_environment()" do node.chef_environment("latte") - node.chef_environment.should == "latte" + expect(node.chef_environment).to eq("latte") end it "should disallow non-strings" do - lambda { node.chef_environment(Hash.new) }.should raise_error(ArgumentError) - lambda { node.chef_environment(42) }.should raise_error(ArgumentError) + expect { node.chef_environment(Hash.new) }.to raise_error(ArgumentError) + expect { node.chef_environment(42) }.to raise_error(ArgumentError) end it "cannot be blank" do - lambda { node.chef_environment("")}.should raise_error(Chef::Exceptions::ValidationFailed) + expect { node.chef_environment("")}.to raise_error(Chef::Exceptions::ValidationFailed) end end describe "attributes" do it "should have attributes" do - node.attribute.should be_a_kind_of(Hash) + expect(node.attribute).to be_a_kind_of(Hash) end it "should allow attributes to be accessed by name or symbol directly on node[]" do node.default["locust"] = "something" - node[:locust].should eql("something") - node["locust"].should eql("something") + expect(node[:locust]).to eql("something") + expect(node["locust"]).to eql("something") end it "should return nil if it cannot find an attribute with node[]" do - node["secret"].should eql(nil) + expect(node["secret"]).to eql(nil) end it "does not allow you to set an attribute via node[]=" do - lambda { node["secret"] = "shush" }.should raise_error(Chef::Exceptions::ImmutableAttributeModification) + expect { node["secret"] = "shush" }.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end it "should allow you to query whether an attribute exists with attribute?" do node.default["locust"] = "something" - node.attribute?("locust").should eql(true) - node.attribute?("no dice").should eql(false) + expect(node.attribute?("locust")).to eql(true) + expect(node.attribute?("no dice")).to eql(false) end it "should let you go deep with attribute?" do node.set["battles"]["people"]["wonkey"] = true - node["battles"]["people"].attribute?("wonkey").should == true - node["battles"]["people"].attribute?("snozzberry").should == false + expect(node["battles"]["people"].attribute?("wonkey")).to eq(true) + expect(node["battles"]["people"].attribute?("snozzberry")).to eq(false) end it "does not allow you to set an attribute via method_missing" do - lambda { node.sunshine = "is bright"}.should raise_error(Chef::Exceptions::ImmutableAttributeModification) + expect { node.sunshine = "is bright"}.to raise_error(Chef::Exceptions::ImmutableAttributeModification) end it "should allow you get get an attribute via method_missing" do node.default.sunshine = "is bright" - node.sunshine.should eql("is bright") + expect(node.sunshine).to eql("is bright") end describe "normal attributes" do it "should allow you to set an attribute with set, without pre-declaring a hash" do node.set[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set an attribute with set_unless" do node.set_unless[:snoopy][:is_a_puppy] = false - node[:snoopy][:is_a_puppy].should == false + expect(node[:snoopy][:is_a_puppy]).to eq(false) end it "should not allow you to set an attribute with set_unless if it already exists" do node.set[:snoopy][:is_a_puppy] = true node.set_unless[:snoopy][:is_a_puppy] = false - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set a value after a set_unless" do # this tests for set_unless_present state bleeding between statements CHEF-3806 node.set_unless[:snoopy][:is_a_puppy] = false node.set[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should let you set a value after a 'dangling' set_unless" do @@ -196,43 +196,43 @@ describe Chef::Node do node.set[:snoopy][:is_a_puppy] = "what" node.set_unless[:snoopy][:is_a_puppy] node.set[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "auto-vivifies attributes created via method syntax" do node.set.fuu.bahrr.baz = "qux" - node.fuu.bahrr.baz.should == "qux" + expect(node.fuu.bahrr.baz).to eq("qux") end it "should let you use tag as a convience method for the tags attribute" do node.normal['tags'] = ['one', 'two'] node.tag('three', 'four') - node['tags'].should == ['one', 'two', 'three', 'four'] + expect(node['tags']).to eq(['one', 'two', 'three', 'four']) end end describe "default attributes" do it "should be set with default, without pre-declaring a hash" do node.default[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set with default_unless without pre-declaring a hash" do node.default_unless[:snoopy][:is_a_puppy] = false - node[:snoopy][:is_a_puppy].should == false + expect(node[:snoopy][:is_a_puppy]).to eq(false) end it "should not allow you to set an attribute with default_unless if it already exists" do node.default[:snoopy][:is_a_puppy] = true node.default_unless[:snoopy][:is_a_puppy] = false - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set a value after a default_unless" do # this tests for set_unless_present state bleeding between statements CHEF-3806 node.default_unless[:snoopy][:is_a_puppy] = false node.default[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set a value after a 'dangling' default_unless" do @@ -240,18 +240,18 @@ describe Chef::Node do node.default[:snoopy][:is_a_puppy] = "what" node.default_unless[:snoopy][:is_a_puppy] node.default[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "auto-vivifies attributes created via method syntax" do node.default.fuu.bahrr.baz = "qux" - node.fuu.bahrr.baz.should == "qux" + expect(node.fuu.bahrr.baz).to eq("qux") end it "accesses force defaults via default!" do node.default![:foo] = "wet bar" node.default[:foo] = "bar" - node[:foo].should == "wet bar" + expect(node[:foo]).to eq("wet bar") end end @@ -259,25 +259,25 @@ describe Chef::Node do describe "override attributes" do it "should be set with override, without pre-declaring a hash" do node.override[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set with override_unless without pre-declaring a hash" do node.override_unless[:snoopy][:is_a_puppy] = false - node[:snoopy][:is_a_puppy].should == false + expect(node[:snoopy][:is_a_puppy]).to eq(false) end it "should not allow you to set an attribute with override_unless if it already exists" do node.override[:snoopy][:is_a_puppy] = true node.override_unless[:snoopy][:is_a_puppy] = false - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set a value after an override_unless" do # this tests for set_unless_present state bleeding between statements CHEF-3806 node.override_unless[:snoopy][:is_a_puppy] = false node.override[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "should allow you to set a value after a 'dangling' override_unless" do @@ -285,24 +285,24 @@ describe Chef::Node do node.override_unless[:snoopy][:is_a_puppy] = "what" node.override_unless[:snoopy][:is_a_puppy] node.override[:snoopy][:is_a_puppy] = true - node[:snoopy][:is_a_puppy].should == true + expect(node[:snoopy][:is_a_puppy]).to eq(true) end it "auto-vivifies attributes created via method syntax" do node.override.fuu.bahrr.baz = "qux" - node.fuu.bahrr.baz.should == "qux" + expect(node.fuu.bahrr.baz).to eq("qux") end it "sets force_overrides via override!" do node.override![:foo] = "wet bar" node.override[:foo] = "bar" - node[:foo].should == "wet bar" + expect(node[:foo]).to eq("wet bar") end end it "should raise an ArgumentError if you ask for an attribute that doesn't exist via method_missing" do - lambda { node.sunshine }.should raise_error(NoMethodError) + expect { node.sunshine }.to raise_error(NoMethodError) end it "should allow you to iterate over attributes with each_attribute" do @@ -312,10 +312,10 @@ describe Chef::Node do node.each_attribute do |a,v| seen_attributes[a] = v end - seen_attributes.should have_key("sunshine") - seen_attributes.should have_key("canada") - seen_attributes["sunshine"].should == "is bright" - seen_attributes["canada"].should == "is a nice place" + expect(seen_attributes).to have_key("sunshine") + expect(seen_attributes).to have_key("canada") + expect(seen_attributes["sunshine"]).to eq("is bright") + expect(seen_attributes["canada"]).to eq("is a nice place") end end @@ -327,62 +327,62 @@ describe Chef::Node do it "consumes the run list portion of a collection of attributes and returns the remainder" do attrs = {"run_list" => [ "role[base]", "recipe[chef::server]" ], "foo" => "bar"} - node.consume_run_list(attrs).should == {"foo" => "bar"} - node.run_list.should == [ "role[base]", "recipe[chef::server]" ] + expect(node.consume_run_list(attrs)).to eq({"foo" => "bar"}) + expect(node.run_list).to eq([ "role[base]", "recipe[chef::server]" ]) end it "should overwrites the run list with the run list it consumes" do node.consume_run_list "recipes" => [ "one", "two" ] node.consume_run_list "recipes" => [ "three" ] - node.run_list.should == [ "three" ] + expect(node.run_list).to eq([ "three" ]) end it "should not add duplicate recipes from the json attributes" do node.run_list << "one" node.consume_run_list "recipes" => [ "one", "two", "three" ] - node.run_list.should == [ "one", "two", "three" ] + expect(node.run_list).to eq([ "one", "two", "three" ]) end it "doesn't change the run list if no run_list is specified in the json" do node.run_list << "role[database]" node.consume_run_list "foo" => "bar" - node.run_list.should == ["role[database]"] + expect(node.run_list).to eq(["role[database]"]) end it "raises an exception if you provide both recipe and run_list attributes, since this is ambiguous" do - lambda { node.consume_run_list "recipes" => "stuff", "run_list" => "other_stuff" }.should raise_error(Chef::Exceptions::AmbiguousRunlistSpecification) + expect { node.consume_run_list "recipes" => "stuff", "run_list" => "other_stuff" }.to raise_error(Chef::Exceptions::AmbiguousRunlistSpecification) end it "should add json attributes to the node" do node.consume_external_attrs(@ohai_data, {"one" => "two", "three" => "four"}) - node.one.should eql("two") - node.three.should eql("four") + expect(node.one).to eql("two") + expect(node.three).to eql("four") end it "should set the tags attribute to an empty array if it is not already defined" do node.consume_external_attrs(@ohai_data, {}) - node.tags.should eql([]) + expect(node.tags).to eql([]) end it "should not set the tags attribute to an empty array if it is already defined" do node.normal[:tags] = [ "radiohead" ] node.consume_external_attrs(@ohai_data, {}) - node.tags.should eql([ "radiohead" ]) + expect(node.tags).to eql([ "radiohead" ]) end it "deep merges attributes instead of overwriting them" do node.consume_external_attrs(@ohai_data, "one" => {"two" => {"three" => "four"}}) - node.one.to_hash.should == {"two" => {"three" => "four"}} + expect(node.one.to_hash).to eq({"two" => {"three" => "four"}}) node.consume_external_attrs(@ohai_data, "one" => {"abc" => "123"}) node.consume_external_attrs(@ohai_data, "one" => {"two" => {"foo" => "bar"}}) - node.one.to_hash.should == {"two" => {"three" => "four", "foo" => "bar"}, "abc" => "123"} + expect(node.one.to_hash).to eq({"two" => {"three" => "four", "foo" => "bar"}, "abc" => "123"}) end it "gives attributes from JSON priority when deep merging" do node.consume_external_attrs(@ohai_data, "one" => {"two" => {"three" => "four"}}) - node.one.to_hash.should == {"two" => {"three" => "four"}} + expect(node.one.to_hash).to eq({"two" => {"three" => "four"}}) node.consume_external_attrs(@ohai_data, "one" => {"two" => {"three" => "forty-two"}}) - node.one.to_hash.should == {"two" => {"three" => "forty-two"}} + expect(node.one.to_hash).to eq({"two" => {"three" => "forty-two"}}) end end @@ -394,21 +394,21 @@ describe Chef::Node do it "sets its platform according to platform detection" do node.consume_external_attrs(@ohai_data, {}) - node.automatic_attrs[:platform].should == 'foobuntu' - node.automatic_attrs[:platform_version].should == '23.42' + expect(node.automatic_attrs[:platform]).to eq('foobuntu') + expect(node.automatic_attrs[:platform_version]).to eq('23.42') end it "consumes the run list from provided json attributes" do node.consume_external_attrs(@ohai_data, {"run_list" => ['recipe[unicorn]']}) - node.run_list.should == ['recipe[unicorn]'] + expect(node.run_list).to eq(['recipe[unicorn]']) end it "saves non-runlist json attrs for later" do expansion = Chef::RunList::RunListExpansion.new('_default', []) - node.run_list.stub(:expand).and_return(expansion) + allow(node.run_list).to receive(:expand).and_return(expansion) node.consume_external_attrs(@ohai_data, {"foo" => "bar"}) node.expand! - node.normal_attrs.should == {"foo" => "bar", "tags" => []} + expect(node.normal_attrs).to eq({"foo" => "bar", "tags" => []}) end end @@ -420,44 +420,44 @@ describe Chef::Node do e.default_attributes("env default key" => "env default value") e.override_attributes("env override key" => "env override value") end - Chef::Environment.should_receive(:load).with("rspec_env").and_return(@environment) + expect(Chef::Environment).to receive(:load).with("rspec_env").and_return(@environment) @expansion = Chef::RunList::RunListExpansion.new("rspec_env", []) node.chef_environment("rspec_env") - node.run_list.stub(:expand).and_return(@expansion) + allow(node.run_list).to receive(:expand).and_return(@expansion) end it "sets the 'recipes' automatic attribute to the recipes in the expanded run_list" do @expansion.recipes << 'recipe[chef::client]' << 'recipe[nginx::default]' node.expand! - node.automatic_attrs[:recipes].should == ['recipe[chef::client]', 'recipe[nginx::default]'] + expect(node.automatic_attrs[:recipes]).to eq(['recipe[chef::client]', 'recipe[nginx::default]']) end it "sets the 'roles' automatic attribute to the expanded role list" do @expansion.instance_variable_set(:@applied_roles, {'arf' => nil, 'countersnark' => nil}) node.expand! - node.automatic_attrs[:roles].sort.should == ['arf', 'countersnark'] + expect(node.automatic_attrs[:roles].sort).to eq(['arf', 'countersnark']) end it "applies default attributes from the environment as environment defaults" do node.expand! - node.attributes.env_default["env default key"].should == "env default value" + expect(node.attributes.env_default["env default key"]).to eq("env default value") end it "applies override attributes from the environment as env overrides" do node.expand! - node.attributes.env_override["env override key"].should == "env override value" + expect(node.attributes.env_override["env override key"]).to eq("env override value") end it "applies default attributes from roles as role defaults" do @expansion.default_attrs["role default key"] = "role default value" node.expand! - node.attributes.role_default["role default key"].should == "role default value" + expect(node.attributes.role_default["role default key"]).to eq("role default value") end it "applies override attributes from roles as role overrides" do @expansion.override_attrs["role override key"] = "role override value" node.expand! - node.attributes.role_override["role override key"].should == "role override value" + expect(node.attributes.role_override["role override key"]).to eq("role override value") end end @@ -472,8 +472,8 @@ describe Chef::Node do node.automatic_attrs[:recipes] = [ "nginx::other_module" ] node.loaded_recipe(:nginx, "module") expect(node.automatic_attrs[:recipes].length).to eq(2) - expect(node.recipe?("nginx::module")).to be_true - expect(node.recipe?("nginx::other_module")).to be_true + expect(node.recipe?("nginx::module")).to be_truthy + expect(node.recipe?("nginx::other_module")).to be_truthy end end @@ -484,11 +484,11 @@ describe Chef::Node do end it "finds the recipe" do - node.recipe?("nginx::module").should be_true + expect(node.recipe?("nginx::module")).to be_truthy end it "does not find a recipe not in the run list" do - node.recipe?("nginx::other_module").should be_false + expect(node.recipe?("nginx::other_module")).to be_falsey end end context "when a recipe is in the expanded run list only" do @@ -498,11 +498,11 @@ describe Chef::Node do end it "finds a recipe in the expanded run list" do - node.recipe?("nginx::module").should be_true + expect(node.recipe?("nginx::module")).to be_truthy end it "does not find a recipe that's not in the run list" do - node.recipe?("nginx::other_module").should be_false + expect(node.recipe?("nginx::other_module")).to be_falsey end end end @@ -516,15 +516,15 @@ describe Chef::Node do end it "removes default attributes" do - node.default.should be_empty + expect(node.default).to be_empty end it "removes override attributes" do - node.override.should be_empty + expect(node.override).to be_empty end it "leaves normal level attributes untouched" do - node[:foo].should == "normal" + expect(node[:foo]).to eq("normal") end end @@ -540,32 +540,32 @@ describe Chef::Node do @environment = Chef::Environment.new @environment.default_attributes = {:default => "from env", :d_env => "env only" } @environment.override_attributes = {:override => "from env", :o_env => "env only"} - Chef::Environment.stub(:load).and_return(@environment) + allow(Chef::Environment).to receive(:load).and_return(@environment) node.apply_expansion_attributes(@expansion) end it "does not nuke role-only default attrs" do - node[:d_role].should == "role only" + expect(node[:d_role]).to eq("role only") end it "does not nuke role-only override attrs" do - node[:o_role].should == "role only" + expect(node[:o_role]).to eq("role only") end it "does not nuke env-only default attrs" do - node[:o_env].should == "env only" + expect(node[:o_env]).to eq("env only") end it "does not nuke role-only override attrs" do - node[:o_env].should == "env only" + expect(node[:o_env]).to eq("env only") end it "gives role defaults precedence over env defaults" do - node[:default].should == "from role" + expect(node[:default]).to eq("from role") end it "gives env overrides precedence over role overrides" do - node[:override].should == "from env" + expect(node[:override]).to eq("from env") end end @@ -585,60 +585,60 @@ describe Chef::Node do end it "sets attributes from the files" do - node.ldap_server.should eql("ops1prod") - node.ldap_basedn.should eql("dc=hjksolutions,dc=com") - node.ldap_replication_password.should eql("forsure") - node.smokey.should eql("robinson") + expect(node.ldap_server).to eql("ops1prod") + expect(node.ldap_basedn).to eql("dc=hjksolutions,dc=com") + expect(node.ldap_replication_password).to eql("forsure") + expect(node.smokey).to eql("robinson") end it "gives a sensible error when attempting to load a missing attributes file" do - lambda { node.include_attribute("nope-this::doesnt-exist") }.should raise_error(Chef::Exceptions::CookbookNotFound) + expect { node.include_attribute("nope-this::doesnt-exist") }.to raise_error(Chef::Exceptions::CookbookNotFound) end end describe "roles" do it "should allow you to query whether or not it has a recipe applied with role?" do node.run_list << "role[sunrise]" - node.role?("sunrise").should eql(true) - node.role?("not at home").should eql(false) + expect(node.role?("sunrise")).to eql(true) + expect(node.role?("not at home")).to eql(false) end it "should allow you to set roles with arguments" do node.run_list << "role[one]" node.run_list << "role[two]" - node.role?("one").should eql(true) - node.role?("two").should eql(true) + expect(node.role?("one")).to eql(true) + expect(node.role?("two")).to eql(true) end end describe "run_list" do it "should have a Chef::RunList of recipes and roles that should be applied" do - node.run_list.should be_a_kind_of(Chef::RunList) + expect(node.run_list).to be_a_kind_of(Chef::RunList) end it "should allow you to query the run list with arguments" do node.run_list "recipe[baz]" - node.run_list?("recipe[baz]").should eql(true) + expect(node.run_list?("recipe[baz]")).to eql(true) end it "should allow you to set the run list with arguments" do node.run_list "recipe[baz]", "role[foo]" - node.run_list?("recipe[baz]").should eql(true) - node.run_list?("role[foo]").should eql(true) + expect(node.run_list?("recipe[baz]")).to eql(true) + expect(node.run_list?("role[foo]")).to eql(true) end end describe "from file" do it "should load a node from a ruby file" do node.from_file(File.expand_path(File.join(CHEF_SPEC_DATA, "nodes", "test.rb"))) - node.name.should eql("test.example.com-short") - node.sunshine.should eql("in") - node.something.should eql("else") - node.run_list.should == ["operations-master", "operations-monitoring"] + expect(node.name).to eql("test.example.com-short") + expect(node.sunshine).to eql("in") + expect(node.something).to eql("else") + expect(node.run_list).to eq(["operations-master", "operations-monitoring"]) end it "should raise an exception if the file cannot be found or read" do - lambda { node.from_file("/tmp/monkeydiving") }.should raise_error(IOError) + expect { node.from_file("/tmp/monkeydiving") }.to raise_error(IOError) end end @@ -666,16 +666,16 @@ describe Chef::Node do it "allows update of everything except name" do node.update_from!(@example) - node.name.should == "orig" - node.chef_environment.should == @example.chef_environment - node.default_attrs.should == @example.default_attrs - node.override_attrs.should == @example.override_attrs - node.normal_attrs.should == @example.normal_attrs - node.run_list.should == @example.run_list + expect(node.name).to eq("orig") + expect(node.chef_environment).to eq(@example.chef_environment) + expect(node.default_attrs).to eq(@example.default_attrs) + expect(node.override_attrs).to eq(@example.override_attrs) + expect(node.normal_attrs).to eq(@example.normal_attrs) + expect(node.run_list).to eq(@example.run_list) end it "should not update the name of the node" do - node.should_not_receive(:name).with(@example.name) + expect(node).not_to receive(:name).with(@example.name) node.update_from!(@example) end end @@ -690,19 +690,19 @@ describe Chef::Node do node.run_list << "role[leninist]" node.run_list << "recipe[stalinist]" h = node.to_hash - h["one"]["two"].should == "three" - h["one"]["four"].should == "six" - h["one"]["eight"].should == "nine" - h["role"].should be_include("marxist") - h["role"].should be_include("leninist") - h["run_list"].should be_include("role[marxist]") - h["run_list"].should be_include("role[leninist]") - h["run_list"].should be_include("recipe[stalinist]") - h["chef_environment"].should == "dev" + expect(h["one"]["two"]).to eq("three") + expect(h["one"]["four"]).to eq("six") + expect(h["one"]["eight"]).to eq("nine") + expect(h["role"]).to be_include("marxist") + expect(h["role"]).to be_include("leninist") + expect(h["run_list"]).to be_include("role[marxist]") + expect(h["run_list"]).to be_include("role[leninist]") + expect(h["run_list"]).to be_include("recipe[stalinist]") + expect(h["chef_environment"]).to eq("dev") end it 'should return an empty array for empty run_list' do - node.to_hash["run_list"].should == [] + expect(node.to_hash["run_list"]).to eq([]) end end @@ -710,13 +710,13 @@ describe Chef::Node do it "should serialize itself as json", :json => true do node.from_file(File.expand_path("nodes/test.example.com.rb", CHEF_SPEC_DATA)) json = Chef::JSONCompat.to_json(node) - json.should =~ /json_class/ - json.should =~ /name/ - json.should =~ /chef_environment/ - json.should =~ /normal/ - json.should =~ /default/ - json.should =~ /override/ - json.should =~ /run_list/ + expect(json).to match(/json_class/) + expect(json).to match(/name/) + expect(json).to match(/chef_environment/) + expect(json).to match(/normal/) + expect(json).to match(/default/) + expect(json).to match(/override/) + expect(json).to match(/run_list/) end it 'should serialize valid json with a run list', :json => true do @@ -725,32 +725,32 @@ describe Chef::Node do node.run_list << {"type" => "role", "name" => 'Cthulu'} node.run_list << {"type" => "role", "name" => 'Hastur'} json = Chef::JSONCompat.to_json(node) - json.should =~ /\"run_list\":\[\"role\[Cthulu\]\",\"role\[Hastur\]\"\]/ + expect(json).to match(/\"run_list\":\[\"role\[Cthulu\]\",\"role\[Hastur\]\"\]/) end it "should serialize the correct run list", :json => true do node.run_list << "role[marxist]" node.run_list << "role[leninist]" node.override_runlist << "role[stalinist]" - node.run_list.should be_include("role[stalinist]") + expect(node.run_list).to be_include("role[stalinist]") json = Chef::JSONCompat.to_json(node) - json.should =~ /\"run_list\":\[\"role\[marxist\]\",\"role\[leninist\]\"\]/ + expect(json).to match(/\"run_list\":\[\"role\[marxist\]\",\"role\[leninist\]\"\]/) end it "merges the override components into a combined override object" do node.attributes.role_override["role override"] = "role override" node.attributes.env_override["env override"] = "env override" node_for_json = node.for_json - node_for_json["override"]["role override"].should == "role override" - node_for_json["override"]["env override"].should == "env override" + expect(node_for_json["override"]["role override"]).to eq("role override") + expect(node_for_json["override"]["env override"]).to eq("env override") end it "merges the default components into a combined default object" do node.attributes.role_default["role default"] = "role default" node.attributes.env_default["env default"] = "env default" node_for_json = node.for_json - node_for_json["default"]["role default"].should == "role default" - node_for_json["default"]["env default"].should == "env default" + expect(node_for_json["default"]["role default"]).to eq("role default") + expect(node_for_json["default"]["env default"]).to eq("env default") end @@ -758,13 +758,13 @@ describe Chef::Node do node.from_file(File.expand_path("nodes/test.example.com.rb", CHEF_SPEC_DATA)) json = Chef::JSONCompat.to_json(node) serialized_node = Chef::JSONCompat.from_json(json) - serialized_node.should be_a_kind_of(Chef::Node) - serialized_node.name.should eql(node.name) - serialized_node.chef_environment.should eql(node.chef_environment) + expect(serialized_node).to be_a_kind_of(Chef::Node) + expect(serialized_node.name).to eql(node.name) + expect(serialized_node.chef_environment).to eql(node.chef_environment) node.each_attribute do |k,v| - serialized_node[k].should eql(v) + expect(serialized_node[k]).to eql(v) end - serialized_node.run_list.should == node.run_list + expect(serialized_node.run_list).to eq(node.run_list) end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -778,45 +778,45 @@ describe Chef::Node do describe "to_s" do it "should turn into a string like node[name]" do node.name("airplane") - node.to_s.should eql("node[airplane]") + expect(node.to_s).to eql("node[airplane]") end end describe "api model" do before(:each) do @rest = double("Chef::REST") - Chef::REST.stub(:new).and_return(@rest) + allow(Chef::REST).to receive(:new).and_return(@rest) @query = double("Chef::Search::Query") - Chef::Search::Query.stub(:new).and_return(@query) + allow(Chef::Search::Query).to receive(:new).and_return(@query) end describe "list" do describe "inflated" do it "should return a hash of node names and objects" do n1 = double("Chef::Node", :name => "one") - @query.should_receive(:search).with(:node).and_yield(n1) + expect(@query).to receive(:search).with(:node).and_yield(n1) r = Chef::Node.list(true) - r["one"].should == n1 + expect(r["one"]).to eq(n1) end end it "should return a hash of node names and urls" do - @rest.should_receive(:get_rest).and_return({ "one" => "http://foo" }) + expect(@rest).to receive(:get_rest).and_return({ "one" => "http://foo" }) r = Chef::Node.list - r["one"].should == "http://foo" + expect(r["one"]).to eq("http://foo") end end describe "load" do it "should load a node by name" do - @rest.should_receive(:get_rest).with("nodes/monkey").and_return("foo") - Chef::Node.load("monkey").should == "foo" + expect(@rest).to receive(:get_rest).with("nodes/monkey").and_return("foo") + expect(Chef::Node.load("monkey")).to eq("foo") end end describe "destroy" do it "should destroy a node" do - @rest.should_receive(:delete_rest).with("nodes/monkey").and_return("foo") + expect(@rest).to receive(:delete_rest).with("nodes/monkey").and_return("foo") node.name("monkey") node.destroy end @@ -825,25 +825,25 @@ describe Chef::Node do describe "save" do it "should update a node if it already exists" do node.name("monkey") - node.stub(:data_for_save).and_return({}) - @rest.should_receive(:put_rest).with("nodes/monkey", {}).and_return("foo") + allow(node).to receive(:data_for_save).and_return({}) + expect(@rest).to receive(:put_rest).with("nodes/monkey", {}).and_return("foo") node.save end it "should not try and create if it can update" do node.name("monkey") - node.stub(:data_for_save).and_return({}) - @rest.should_receive(:put_rest).with("nodes/monkey", {}).and_return("foo") - @rest.should_not_receive(:post_rest) + allow(node).to receive(:data_for_save).and_return({}) + expect(@rest).to receive(:put_rest).with("nodes/monkey", {}).and_return("foo") + expect(@rest).not_to receive(:post_rest) node.save end it "should create if it cannot update" do node.name("monkey") - node.stub(:data_for_save).and_return({}) + allow(node).to receive(:data_for_save).and_return({}) exception = double("404 error", :code => "404") - @rest.should_receive(:put_rest).and_raise(Net::HTTPServerException.new("foo", exception)) - @rest.should_receive(:post_rest).with("nodes", {}) + expect(@rest).to receive(:put_rest).and_raise(Net::HTTPServerException.new("foo", exception)) + expect(@rest).to receive(:post_rest).with("nodes", {}) node.save end @@ -856,8 +856,8 @@ describe Chef::Node do end it "should not save" do node.name("monkey") - @rest.should_not_receive(:put_rest) - @rest.should_not_receive(:post_rest) + expect(@rest).not_to receive(:put_rest) + expect(@rest).not_to receive(:post_rest) node.save end end @@ -900,8 +900,8 @@ describe Chef::Node do } node.name("picky-monkey") - node.stub(:for_json).and_return(data) - @rest.should_receive(:put_rest).with("nodes/picky-monkey", selected_data).and_return("foo") + allow(node).to receive(:for_json).and_return(data) + expect(@rest).to receive(:put_rest).with("nodes/picky-monkey", selected_data).and_return("foo") node.save end @@ -923,8 +923,8 @@ describe Chef::Node do } node.name("picky-monkey") - node.stub(:for_json).and_return(data) - @rest.should_receive(:put_rest).with("nodes/picky-monkey", selected_data).and_return("foo") + allow(node).to receive(:for_json).and_return(data) + expect(@rest).to receive(:put_rest).with("nodes/picky-monkey", selected_data).and_return("foo") node.save end end diff --git a/spec/unit/platform/query_helpers_spec.rb b/spec/unit/platform/query_helpers_spec.rb index 6adea5eecf..7aafc287ea 100644 --- a/spec/unit/platform/query_helpers_spec.rb +++ b/spec/unit/platform/query_helpers_spec.rb @@ -20,9 +20,9 @@ require 'spec_helper' describe "Chef::Platform#windows_server_2003?" do it "returns false early when not on windows" do - Chef::Platform.stub(:windows?).and_return(false) + allow(Chef::Platform).to receive(:windows?).and_return(false) expect(Chef::Platform).not_to receive(:require) - expect(Chef::Platform.windows_server_2003?).to be_false + expect(Chef::Platform.windows_server_2003?).to be_falsey end # CHEF-4888: Need to call WIN32OLE.ole_initialize in new threads @@ -34,14 +34,14 @@ end describe 'Chef::Platform#supports_dsc?' do it 'returns false if powershell is not present' do node = Chef::Node.new - Chef::Platform.supports_dsc?(node).should be_false + expect(Chef::Platform.supports_dsc?(node)).to be_falsey end ['1.0', '2.0', '3.0'].each do |version| it "returns false for Powershell #{version}" do node = Chef::Node.new node.automatic[:languages][:powershell][:version] = version - Chef::Platform.supports_dsc?(node).should be_false + expect(Chef::Platform.supports_dsc?(node)).to be_falsey end end @@ -49,7 +49,7 @@ describe 'Chef::Platform#supports_dsc?' do it "returns true for Powershell #{version}" do node = Chef::Node.new node.automatic[:languages][:powershell][:version] = version - Chef::Platform.supports_dsc?(node).should be_true + expect(Chef::Platform.supports_dsc?(node)).to be_truthy end end end diff --git a/spec/unit/platform_spec.rb b/spec/unit/platform_spec.rb index 9a65cbe878..fb65ef0fea 100644 --- a/spec/unit/platform_spec.rb +++ b/spec/unit/platform_spec.rb @@ -41,7 +41,7 @@ describe "Chef::Platform supports" do :ibm_powerkvm ].each do |platform| it "#{platform}" do - Chef::Platform.platforms.should have_key(platform) + expect(Chef::Platform.platforms).to have_key(platform) end end end @@ -86,57 +86,57 @@ describe Chef::Platform do it "should allow you to look up a platform by name and version, returning the provider map for it" do pmap = Chef::Platform.find("Darwin", "9.2.2") - pmap.should be_a_kind_of(Hash) - pmap[:file].should eql("darwinian") + expect(pmap).to be_a_kind_of(Hash) + expect(pmap[:file]).to eql("darwinian") end it "should allow you to look up a platform by name and version using \"greater than\" style operators" do pmap = Chef::Platform.find("Darwin", "11.1.0") - pmap.should be_a_kind_of(Hash) - pmap[:file].should eql("new_darwinian") + expect(pmap).to be_a_kind_of(Hash) + expect(pmap[:file]).to eql("new_darwinian") end it "should use the default providers for an os if the specific version does not exist" do pmap = Chef::Platform.find("Darwin", "1") - pmap.should be_a_kind_of(Hash) - pmap[:file].should eql("old school") + expect(pmap).to be_a_kind_of(Hash) + expect(pmap[:file]).to eql("old school") end it "should use the default providers if the os doesn't give me a default, but does exist" do pmap = Chef::Platform.find("mars_volta", "1") - pmap.should be_a_kind_of(Hash) - pmap[:file].should eql(Chef::Provider::File) + expect(pmap).to be_a_kind_of(Hash) + expect(pmap[:file]).to eql(Chef::Provider::File) end it "should use the default provider if the os does not exist" do pmap = Chef::Platform.find("AIX", "1") - pmap.should be_a_kind_of(Hash) - pmap[:file].should eql(Chef::Provider::File) + expect(pmap).to be_a_kind_of(Hash) + expect(pmap[:file]).to eql(Chef::Provider::File) end it "should merge the defaults for an os with the specific version" do pmap = Chef::Platform.find("Darwin", "9.2.2") - pmap[:file].should eql("darwinian") - pmap[:snicker].should eql("snack") + expect(pmap[:file]).to eql("darwinian") + expect(pmap[:snicker]).to eql("snack") end it "should merge the defaults for an os with the universal defaults" do pmap = Chef::Platform.find("Darwin", "9.2.2") - pmap[:file].should eql("darwinian") - pmap[:pax].should eql("brittania") + expect(pmap[:file]).to eql("darwinian") + expect(pmap[:pax]).to eql("brittania") end it "should allow you to look up a provider for a platform directly by symbol" do - Chef::Platform.find_provider("Darwin", "9.2.2", :file).should eql("darwinian") + expect(Chef::Platform.find_provider("Darwin", "9.2.2", :file)).to eql("darwinian") end it "should raise an exception if a provider cannot be found for a resource type" do - lambda { Chef::Platform.find_provider("Darwin", "9.2.2", :coffee) }.should raise_error(ArgumentError) + expect { Chef::Platform.find_provider("Darwin", "9.2.2", :coffee) }.to raise_error(ArgumentError) end it "should look up a provider for a resource with a Chef::Resource object" do kitty = Chef::Resource::Cat.new("loulou") - Chef::Platform.find_provider("Darwin", "9.2.2", kitty).should eql("nice") + expect(Chef::Platform.find_provider("Darwin", "9.2.2", kitty)).to eql("nice") end it "should look up a provider with a node and a Chef::Resource object" do @@ -145,21 +145,21 @@ describe Chef::Platform do node.name("Intel") node.automatic_attrs[:platform] = "mac_os_x" node.automatic_attrs[:platform_version] = "9.2.2" - Chef::Platform.find_provider_for_node(node, kitty).should eql("nice") + expect(Chef::Platform.find_provider_for_node(node, kitty)).to eql("nice") end it "should not throw an exception when the platform version has an unknown format" do - Chef::Platform.find_provider(:darwin, "bad-version", :file).should eql("old school") + expect(Chef::Platform.find_provider(:darwin, "bad-version", :file)).to eql("old school") end it "should prefer an explicit provider" do kitty = Chef::Resource::Cat.new("loulou") - kitty.stub(:provider).and_return(Chef::Provider::File) + allow(kitty).to receive(:provider).and_return(Chef::Provider::File) node = Chef::Node.new node.name("Intel") node.automatic_attrs[:platform] = "mac_os_x" node.automatic_attrs[:platform_version] = "9.2.2" - Chef::Platform.find_provider_for_node(node, kitty).should eql(Chef::Provider::File) + expect(Chef::Platform.find_provider_for_node(node, kitty)).to eql(Chef::Provider::File) end it "should look up a provider based on the resource name if nothing else matches" do @@ -170,7 +170,7 @@ describe Chef::Platform do node.name("Intel") node.automatic_attrs[:platform] = "mac_os_x" node.automatic_attrs[:platform_version] = "8.5" - Chef::Platform.find_provider_for_node(node, kitty).should eql(Chef::Provider::Cat) + expect(Chef::Platform.find_provider_for_node(node, kitty)).to eql(Chef::Provider::Cat) end def setup_file_resource @@ -184,26 +184,26 @@ describe Chef::Platform do it "returns a provider object given a Chef::Resource object which has a valid run context and an action" do file, run_context = setup_file_resource provider = Chef::Platform.provider_for_resource(file, :foo) - provider.should be_an_instance_of(Chef::Provider::File) - provider.new_resource.should equal(file) - provider.run_context.should equal(run_context) + expect(provider).to be_an_instance_of(Chef::Provider::File) + expect(provider.new_resource).to equal(file) + expect(provider.run_context).to equal(run_context) end it "returns a provider object given a Chef::Resource object which has a valid run context without an action" do file, run_context = setup_file_resource provider = Chef::Platform.provider_for_resource(file) - provider.should be_an_instance_of(Chef::Provider::File) - provider.new_resource.should equal(file) - provider.run_context.should equal(run_context) + expect(provider).to be_an_instance_of(Chef::Provider::File) + expect(provider.new_resource).to equal(file) + expect(provider.run_context).to equal(run_context) end it "raises an error when trying to find the provider for a resource with no run context" do file = Chef::Resource::File.new("whateva") - lambda {Chef::Platform.provider_for_resource(file)}.should raise_error(ArgumentError) + expect {Chef::Platform.provider_for_resource(file)}.to raise_error(ArgumentError) end it "does not support finding a provider by resource and node -- a run context is required" do - lambda {Chef::Platform.provider_for_node('node', 'resource')}.should raise_error(NotImplementedError) + expect {Chef::Platform.provider_for_node('node', 'resource')}.to raise_error(NotImplementedError) end it "should update the provider map with map" do @@ -213,18 +213,18 @@ describe Chef::Platform do :resource => :file, :provider => "masterful" ) - Chef::Platform.platforms[:darwin]["9.2.2"][:file].should eql("masterful") + expect(Chef::Platform.platforms[:darwin]["9.2.2"][:file]).to eql("masterful") Chef::Platform.set( :platform => :darwin, :resource => :file, :provider => "masterful" ) - Chef::Platform.platforms[:darwin][:default][:file].should eql("masterful") + expect(Chef::Platform.platforms[:darwin][:default][:file]).to eql("masterful") Chef::Platform.set( :resource => :file, :provider => "masterful" ) - Chef::Platform.platforms[:default][:file].should eql("masterful") + expect(Chef::Platform.platforms[:default][:file]).to eql("masterful") Chef::Platform.set( :platform => :hero, @@ -232,13 +232,13 @@ describe Chef::Platform do :resource => :file, :provider => "masterful" ) - Chef::Platform.platforms[:hero]["9.2.2"][:file].should eql("masterful") + expect(Chef::Platform.platforms[:hero]["9.2.2"][:file]).to eql("masterful") Chef::Platform.set( :resource => :file, :provider => "masterful" ) - Chef::Platform.platforms[:default][:file].should eql("masterful") + expect(Chef::Platform.platforms[:default][:file]).to eql("masterful") Chef::Platform.platforms = {} @@ -246,11 +246,11 @@ describe Chef::Platform do :resource => :file, :provider => "masterful" ) - Chef::Platform.platforms[:default][:file].should eql("masterful") + expect(Chef::Platform.platforms[:default][:file]).to eql("masterful") Chef::Platform.platforms = { :neurosis => {} } Chef::Platform.set(:platform => :neurosis, :resource => :package, :provider => "masterful") - Chef::Platform.platforms[:neurosis][:default][:package].should eql("masterful") + expect(Chef::Platform.platforms[:neurosis][:default][:package]).to eql("masterful") end @@ -260,8 +260,8 @@ describe Chef::Platform do :platform => :default, :provider => "new school" ) - Chef::Platform.platforms[:default][:file].should eql("new school") - Chef::Platform.platforms[:default][:cat].should eql("nice") + expect(Chef::Platform.platforms[:default][:file]).to eql("new school") + expect(Chef::Platform.platforms[:default][:cat]).to eql("nice") end end @@ -270,36 +270,36 @@ describe Chef::Platform do it "should use the solaris package provider on Solaris <11" do pmap = Chef::Platform.find("Solaris2", "5.9") - pmap[:package].should eql(Chef::Provider::Package::Solaris) + expect(pmap[:package]).to eql(Chef::Provider::Package::Solaris) end it "should use the IPS package provider on Solaris 11" do pmap = Chef::Platform.find("Solaris2", "5.11") - pmap[:package].should eql(Chef::Provider::Package::Ips) + expect(pmap[:package]).to eql(Chef::Provider::Package::Ips) end it "should use the Redhat service provider on SLES11" do 1.upto(3) do |sp| pmap = Chef::Platform.find("SUSE", "11.#{sp}") - pmap[:service].should eql(Chef::Provider::Service::Redhat) + expect(pmap[:service]).to eql(Chef::Provider::Service::Redhat) end end it "should use the Systemd service provider on SLES12" do pmap = Chef::Platform.find("SUSE", "12.0") - pmap[:service].should eql(Chef::Provider::Service::Systemd) + expect(pmap[:service]).to eql(Chef::Provider::Service::Systemd) end it "should use the SUSE group provider on SLES11" do 1.upto(3) do |sp| pmap = Chef::Platform.find("SUSE", "11.#{sp}") - pmap[:group].should eql(Chef::Provider::Group::Suse) + expect(pmap[:group]).to eql(Chef::Provider::Group::Suse) end end it "should use the Gpasswd group provider on SLES12" do pmap = Chef::Platform.find("SUSE", "12.0") - pmap[:group].should eql(Chef::Provider::Group::Gpasswd) + expect(pmap[:group]).to eql(Chef::Provider::Group::Gpasswd) end end diff --git a/spec/unit/policy_builder/expand_node_object_spec.rb b/spec/unit/policy_builder/expand_node_object_spec.rb index a1e0b881d5..8e9fdc305e 100644 --- a/spec/unit/policy_builder/expand_node_object_spec.rb +++ b/spec/unit/policy_builder/expand_node_object_spec.rb @@ -73,7 +73,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do it "creates a new in-memory node object with the given name" do policy_builder.load_node - policy_builder.node.name.should == node_name + expect(policy_builder.node.name).to eq(node_name) end end @@ -83,9 +83,9 @@ describe Chef::PolicyBuilder::ExpandNodeObject do let(:node) { Chef::Node.new.tap { |n| n.name(node_name) } } it "loads or creates a node on the server" do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) policy_builder.load_node - policy_builder.node.should == node + expect(policy_builder.node).to eq(node) end end @@ -95,7 +95,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do # XXX: Chef::Client just needs to be able to call this, it doesn't depend on the return value. it "builds the node and returns the updated node object" do - pending + skip end end @@ -133,7 +133,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do end before do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) policy_builder.load_node end @@ -167,7 +167,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do before do Chef::Config[:environment] = configured_environment - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) policy_builder.load_node policy_builder.build_node end @@ -186,7 +186,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do end it "reports that a temporary_policy is not being used" do - expect(policy_builder.temporary_policy?).to be_false + expect(policy_builder.temporary_policy?).to be_falsey end describe "when the given run list is not in expanded form" do @@ -210,7 +210,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do node.override_attrs = original_override_attrs node.run_list(primary_runlist) - node.should_receive(:expand!).with("server") do + expect(node).to receive(:expand!).with("server") do node.run_list("recipe[from_role::default]") expansion end @@ -248,7 +248,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do end it "reports that a temporary policy is being used" do - expect(policy_builder.temporary_policy?).to be_true + expect(policy_builder.temporary_policy?).to be_truthy end end @@ -267,7 +267,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do let(:environment) do environment = Chef::Environment.new.tap {|e| e.name("prod") } - Chef::Environment.should_receive(:load).with("prod").and_return(environment) + expect(Chef::Environment).to receive(:load).with("prod").and_return(environment) environment end @@ -302,27 +302,27 @@ describe Chef::PolicyBuilder::ExpandNodeObject do let(:cookbook_synchronizer) { double("CookbookSynchronizer") } before do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) - policy_builder.stub(:api_service).and_return(chef_http) + allow(policy_builder).to receive(:api_service).and_return(chef_http) policy_builder.load_node policy_builder.build_node run_list_expansion = policy_builder.run_list_expansion - chef_http.should_receive(:post).with(cookbook_resolve_url, cookbook_resolve_post_data).and_return(cookbook_hash) - Chef::CookbookSynchronizer.should_receive(:new).with(cookbook_hash, events).and_return(cookbook_synchronizer) - cookbook_synchronizer.should_receive(:sync_cookbooks) + expect(chef_http).to receive(:post).with(cookbook_resolve_url, cookbook_resolve_post_data).and_return(cookbook_hash) + expect(Chef::CookbookSynchronizer).to receive(:new).with(cookbook_hash, events).and_return(cookbook_synchronizer) + expect(cookbook_synchronizer).to receive(:sync_cookbooks) - Chef::RunContext.any_instance.should_receive(:load).with(run_list_expansion) + expect_any_instance_of(Chef::RunContext).to receive(:load).with(run_list_expansion) policy_builder.setup_run_context end it "configures FileVendor to fetch files remotely" do manifest = double("cookbook manifest") - Chef::Cookbook::RemoteFileVendor.should_receive(:new).with(manifest, chef_http) + expect(Chef::Cookbook::RemoteFileVendor).to receive(:new).with(manifest, chef_http) Chef::Cookbook::FileVendor.create_from_manifest(manifest) end @@ -333,4 +333,3 @@ describe Chef::PolicyBuilder::ExpandNodeObject do end end - diff --git a/spec/unit/policy_builder/policyfile_spec.rb b/spec/unit/policy_builder/policyfile_spec.rb index f02c79ef12..5e2844201d 100644 --- a/spec/unit/policy_builder/policyfile_spec.rb +++ b/spec/unit/policy_builder/policyfile_spec.rb @@ -96,7 +96,7 @@ describe Chef::PolicyBuilder::Policyfile do http = double("Chef::REST") server_url = "https://api.opscode.com/organizations/example" Chef::Config[:chef_server_url] = server_url - Chef::REST.should_receive(:new).with(server_url).and_return(http) + expect(Chef::REST).to receive(:new).with(server_url).and_return(http) expect(policy_builder.http_api).to eq(http) end @@ -107,7 +107,7 @@ describe Chef::PolicyBuilder::Policyfile do end it "always gives `false` for #temporary_policy?" do - expect(initialize_pb.temporary_policy?).to be_false + expect(initialize_pb.temporary_policy?).to be_falsey end context "chef-solo" do @@ -168,15 +168,15 @@ describe Chef::PolicyBuilder::Policyfile do before do # TODO: agree on this name and logic. Chef::Config[:deployment_group] = "example-policy-stage" - policy_builder.stub(:http_api).and_return(http_api) + allow(policy_builder).to receive(:http_api).and_return(http_api) end context "when the deployment group cannot be loaded" do let(:error404) { Net::HTTPServerException.new("404 message", :body) } before do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) - http_api.should_receive(:get). + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) + expect(http_api).to receive(:get). with("data/policyfiles/example-policy-stage"). and_raise(error404) end @@ -186,7 +186,7 @@ describe Chef::PolicyBuilder::Policyfile do end it "sends error message to the event system" do - events.should_receive(:node_load_failed).with(node_name, an_instance_of(err_namespace::ConfigurationError), Chef::Config) + expect(events).to receive(:node_load_failed).with(node_name, an_instance_of(err_namespace::ConfigurationError), Chef::Config) expect { policy_builder.load_node }.to raise_error(err_namespace::ConfigurationError) end @@ -195,7 +195,7 @@ describe Chef::PolicyBuilder::Policyfile do describe "when the deployment_group is not configured" do before do Chef::Config[:deployment_group] = nil - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) end it "errors while loading the node" do @@ -206,14 +206,14 @@ describe Chef::PolicyBuilder::Policyfile do it "passes error information to the event system" do # TODO: also make sure something acceptable happens with the error formatters err_class = err_namespace::ConfigurationError - events.should_receive(:node_load_failed).with(node_name, an_instance_of(err_class), Chef::Config) + expect(events).to receive(:node_load_failed).with(node_name, an_instance_of(err_class), Chef::Config) expect { policy_builder.load_node }.to raise_error(err_class) end end context "and a deployment_group is configured" do before do - http_api.should_receive(:get).with("data/policyfiles/example-policy-stage").and_return(parsed_policyfile_json) + expect(http_api).to receive(:get).with("data/policyfiles/example-policy-stage").and_return(parsed_policyfile_json) end it "fetches the policy file from a data bag item" do @@ -239,7 +239,7 @@ describe Chef::PolicyBuilder::Policyfile do end it "implements #expand_run_list in a manner compatible with ExpandNodeObject" do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) policy_builder.load_node expect(policy_builder.expand_run_list).to respond_to(:recipes) expect(policy_builder.expand_run_list.recipes).to eq(["example1::default", "example2::server"]) @@ -278,7 +278,7 @@ describe Chef::PolicyBuilder::Policyfile do describe "building the node object" do before do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) policy_builder.load_node policy_builder.build_node @@ -339,7 +339,7 @@ describe Chef::PolicyBuilder::Policyfile do let(:error404) { Net::HTTPServerException.new("404 message", :body) } before do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) # Remove references to example2 cookbook because we're iterating # over a Hash data structure and on ruby 1.8.7 iteration order will @@ -350,7 +350,7 @@ describe Chef::PolicyBuilder::Policyfile do policy_builder.load_node policy_builder.build_node - http_api.should_receive(:get).with("cookbooks/example1/#{example1_xyz_version}"). + expect(http_api).to receive(:get).with("cookbooks/example1/#{example1_xyz_version}"). and_raise(error404) end @@ -362,17 +362,17 @@ describe Chef::PolicyBuilder::Policyfile do context "and the cookbooks can be fetched" do before do - Chef::Node.should_receive(:find_or_create).with(node_name).and_return(node) + expect(Chef::Node).to receive(:find_or_create).with(node_name).and_return(node) policy_builder.load_node policy_builder.build_node - http_api.should_receive(:get).with("cookbooks/example1/#{example1_xyz_version}"). + expect(http_api).to receive(:get).with("cookbooks/example1/#{example1_xyz_version}"). and_return(example1_cookbook_object) - http_api.should_receive(:get).with("cookbooks/example2/#{example2_xyz_version}"). + expect(http_api).to receive(:get).with("cookbooks/example2/#{example2_xyz_version}"). and_return(example2_cookbook_object) - Chef::CookbookSynchronizer.stub(:new). + allow(Chef::CookbookSynchronizer).to receive(:new). with(expected_cookbook_hash, events). and_return(cookbook_synchronizer) end @@ -382,13 +382,13 @@ describe Chef::PolicyBuilder::Policyfile do end it "syncs the desired cookbooks via CookbookSynchronizer" do - cookbook_synchronizer.should_receive(:sync_cookbooks) + expect(cookbook_synchronizer).to receive(:sync_cookbooks) policy_builder.sync_cookbooks end it "builds a run context" do - cookbook_synchronizer.should_receive(:sync_cookbooks) - Chef::RunContext.any_instance.should_receive(:load).with(policy_builder.run_list_expansion_ish) + expect(cookbook_synchronizer).to receive(:sync_cookbooks) + expect_any_instance_of(Chef::RunContext).to receive(:load).with(policy_builder.run_list_expansion_ish) run_context = policy_builder.setup_run_context expect(run_context.node).to eq(node) expect(run_context.cookbook_collection.keys).to match_array(["example1", "example2"]) diff --git a/spec/unit/provider/directory_spec.rb b/spec/unit/provider/directory_spec.rb index 33df776ed4..98f860bc75 100644 --- a/spec/unit/provider/directory_spec.rb +++ b/spec/unit/provider/directory_spec.rb @@ -42,7 +42,7 @@ describe Chef::Provider::Directory do end it "describes the directory's access rights" do - pending + skip end end diff --git a/spec/unit/provider/dsc_script_spec.rb b/spec/unit/provider/dsc_script_spec.rb index dab2007920..d018c8ad54 100644 --- a/spec/unit/provider/dsc_script_spec.rb +++ b/spec/unit/provider/dsc_script_spec.rb @@ -39,21 +39,21 @@ describe Chef::Provider::DscScript do it "describes the resource as converged if there were 0 DSC resources" do allow(provider).to receive(:run_configuration).with(:test).and_return([]) provider.load_current_resource - expect(provider.instance_variable_get('@resource_converged')).to be_true + expect(provider.instance_variable_get('@resource_converged')).to be_truthy end it "describes the resource as not converged if there is 1 DSC resources that is converged" do dsc_resource_info = Chef::Util::DSC::ResourceInfo.new('resource', false, ['nothing will change something']) allow(provider).to receive(:run_configuration).with(:test).and_return([dsc_resource_info]) provider.load_current_resource - expect(provider.instance_variable_get('@resource_converged')).to be_true + expect(provider.instance_variable_get('@resource_converged')).to be_truthy end it "describes the resource as not converged if there is 1 DSC resources that is not converged" do dsc_resource_info = Chef::Util::DSC::ResourceInfo.new('resource', true, ['will change something']) allow(provider).to receive(:run_configuration).with(:test).and_return([dsc_resource_info]) provider.load_current_resource - expect(provider.instance_variable_get('@resource_converged')).to be_false + expect(provider.instance_variable_get('@resource_converged')).to be_falsey end it "describes the resource as not converged if there are any DSC resources that are not converged" do @@ -62,7 +62,7 @@ describe Chef::Provider::DscScript do allow(provider).to receive(:run_configuration).with(:test).and_return([dsc_resource_info1, dsc_resource_info2]) provider.load_current_resource - expect(provider.instance_variable_get('@resource_converged')).to be_false + expect(provider.instance_variable_get('@resource_converged')).to be_falsey end it "describes the resource as converged if all DSC resources that are converged" do @@ -71,7 +71,7 @@ describe Chef::Provider::DscScript do allow(provider).to receive(:run_configuration).with(:test).and_return([dsc_resource_info1, dsc_resource_info2]) provider.load_current_resource - expect(provider.instance_variable_get('@resource_converged')).to be_true + expect(provider.instance_variable_get('@resource_converged')).to be_truthy end end diff --git a/spec/unit/provider/env_spec.rb b/spec/unit/provider/env_spec.rb index 22fed4b7ac..19233dfba9 100644 --- a/spec/unit/provider/env_spec.rb +++ b/spec/unit/provider/env_spec.rb @@ -30,7 +30,7 @@ describe Chef::Provider::Env do end it "assumes the key_name exists by default" do - expect(@provider.key_exists).to be_true + expect(@provider.key_exists).to be_truthy end describe "when loading the current status" do @@ -55,13 +55,13 @@ describe Chef::Provider::Env do it "should check if the key_name exists" do expect(@provider).to receive(:env_key_exists).with("FOO").and_return(true) @provider.load_current_resource - expect(@provider.key_exists).to be_true + expect(@provider.key_exists).to be_truthy end it "should flip the value of exists if the key does not exist" do expect(@provider).to receive(:env_key_exists).with("FOO").and_return(false) @provider.load_current_resource - expect(@provider.key_exists).to be_false + expect(@provider.key_exists).to be_falsey end it "should return the current resource" do @@ -230,25 +230,25 @@ describe Chef::Provider::Env do end it "should return false if the values are equal" do - expect(@provider.requires_modify_or_create?).to be_false + expect(@provider.requires_modify_or_create?).to be_falsey end it "should return true if the values not are equal" do @new_resource.value("C:/elsewhere") - expect(@provider.requires_modify_or_create?).to be_true + expect(@provider.requires_modify_or_create?).to be_truthy end it "should return false if the current value contains the element" do @new_resource.delim(";") @current_resource.value("C:/bar;C:/foo;C:/baz") - expect(@provider.requires_modify_or_create?).to be_false + expect(@provider.requires_modify_or_create?).to be_falsey end it "should return true if the current value does not contain the element" do @new_resource.delim(";") @current_resource.value("C:/biz;C:/foo/bin;C:/baz") - expect(@provider.requires_modify_or_create?).to be_true + expect(@provider.requires_modify_or_create?).to be_truthy end context "when new_resource's value contains the delimiter" do @@ -256,14 +256,14 @@ describe Chef::Provider::Env do @new_resource.value("C:/biz;C:/baz") @new_resource.delim(";") @current_resource.value("C:/biz;C:/foo/bin;C:/baz") - expect(@provider.requires_modify_or_create?).to be_false + expect(@provider.requires_modify_or_create?).to be_falsey end it "should return true if any of the new values are not contained" do @new_resource.value("C:/biz;C:/baz;C:/bin") @new_resource.delim(";") @current_resource.value("C:/biz;C:/foo/bin;C:/baz") - expect(@provider.requires_modify_or_create?).to be_true + expect(@provider.requires_modify_or_create?).to be_truthy end end end diff --git a/spec/unit/provider/file/content_spec.rb b/spec/unit/provider/file/content_spec.rb index 0f2fd6632c..db0753bf8c 100644 --- a/spec/unit/provider/file/content_spec.rb +++ b/spec/unit/provider/file/content_spec.rb @@ -66,14 +66,14 @@ describe Chef::Provider::File::Content do it "returns a tempfile in the tempdir when :file_staging_uses_destdir is not set" do Chef::Config[:file_staging_uses_destdir] = false - expect(content.tempfile.path.start_with?(Dir::tmpdir)).to be_true - expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be_false + expect(content.tempfile.path.start_with?(Dir::tmpdir)).to be_truthy + expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be_falsey end it "returns a tempfile in the destdir when :file_desployment_uses_destdir is not set" do Chef::Config[:file_staging_uses_destdir] = true - expect(content.tempfile.path.start_with?(Dir::tmpdir)).to be_false - expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be_true + expect(content.tempfile.path.start_with?(Dir::tmpdir)).to be_falsey + expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be_truthy end end diff --git a/spec/unit/provider/git_spec.rb b/spec/unit/provider/git_spec.rb index bfbf531389..1e282c098d 100644 --- a/spec/unit/provider/git_spec.rb +++ b/spec/unit/provider/git_spec.rb @@ -621,21 +621,21 @@ SHAS describe "when check remote command returns with status 2" do it "returns true" do allow(@command_response).to receive(:exitstatus) { 2 } - expect(@provider.multiple_remotes?(@command_response)).to be_true + expect(@provider.multiple_remotes?(@command_response)).to be_truthy end end describe "when check remote command returns with status 0" do it "returns false" do allow(@command_response).to receive(:exitstatus) { 0 } - expect(@provider.multiple_remotes?(@command_response)).to be_false + expect(@provider.multiple_remotes?(@command_response)).to be_falsey end end describe "when check remote command returns with status 0" do it "returns false" do allow(@command_response).to receive(:exitstatus) { 1 } - expect(@provider.multiple_remotes?(@command_response)).to be_false + expect(@provider.multiple_remotes?(@command_response)).to be_falsey end end end @@ -649,7 +649,7 @@ SHAS it "returns true" do allow(@command_response).to receive(:exitstatus) { 0 } allow(@command_response).to receive(:stdout) { @resource.repository } - expect(@provider.remote_matches?(@resource.repository, @command_response)).to be_true + expect(@provider.remote_matches?(@resource.repository, @command_response)).to be_truthy end end @@ -657,7 +657,7 @@ SHAS it "returns false" do allow(@command_response).to receive(:exitstatus) { 0 } allow(@command_response).to receive(:stdout) { @resource.repository + "test" } - expect(@provider.remote_matches?(@resource.repository, @command_response)).to be_false + expect(@provider.remote_matches?(@resource.repository, @command_response)).to be_falsey end end end diff --git a/spec/unit/provider/group/dscl_spec.rb b/spec/unit/provider/group/dscl_spec.rb index acd1ba3859..e09365a828 100644 --- a/spec/unit/provider/group/dscl_spec.rb +++ b/spec/unit/provider/group/dscl_spec.rb @@ -129,15 +129,15 @@ describe Chef::Provider::Group::Dscl do end it "should return true for a used gid number" do - expect(@provider.gid_used?(500)).to be_true + expect(@provider.gid_used?(500)).to be_truthy end it "should return false for an unused gid number" do - expect(@provider.gid_used?(501)).to be_false + expect(@provider.gid_used?(501)).to be_falsey end it "should return false if not given any valid gid number" do - expect(@provider.gid_used?(nil)).to be_false + expect(@provider.gid_used?(nil)).to be_falsey end end diff --git a/spec/unit/provider/group_spec.rb b/spec/unit/provider/group_spec.rb index e20486fd4a..b36bfe364b 100644 --- a/spec/unit/provider/group_spec.rb +++ b/spec/unit/provider/group_spec.rb @@ -45,7 +45,7 @@ describe Chef::Provider::User do end it "assumes the group exists by default" do - expect(@provider.group_exists).to be_true + expect(@provider.group_exists).to be_truthy end describe "when establishing the current state of the group" do @@ -76,7 +76,7 @@ describe Chef::Provider::User do it "should flip the value of exists if it cannot be found in /etc/group" do allow(Etc).to receive(:getgrnam).and_raise(ArgumentError) @provider.load_current_resource - expect(@provider.group_exists).to be_false + expect(@provider.group_exists).to be_falsey end it "should return the current resource" do @@ -88,42 +88,42 @@ describe Chef::Provider::User do [ :gid, :members ].each do |attribute| it "should return true if #{attribute} doesn't match" do allow(@current_resource).to receive(attribute).and_return("looooooooooooooooooool") - expect(@provider.compare_group).to be_true + expect(@provider.compare_group).to be_truthy end end it "should return false if gid and members are equal" do - expect(@provider.compare_group).to be_false + expect(@provider.compare_group).to be_falsey end it "should coerce an integer to a string for comparison" do allow(@current_resource).to receive(:gid).and_return("500") - expect(@provider.compare_group).to be_false + expect(@provider.compare_group).to be_falsey end it "should return false if append is true and the group member(s) already exists" do @current_resource.members << "extra_user" allow(@new_resource).to receive(:append).and_return(true) - expect(@provider.compare_group).to be_false + expect(@provider.compare_group).to be_falsey end it "should return true if append is true and the group member(s) do not already exist" do @new_resource.members << "extra_user" allow(@new_resource).to receive(:append).and_return(true) - expect(@provider.compare_group).to be_true + expect(@provider.compare_group).to be_truthy end it "should return false if append is true and excluded_members include a non existing member" do @new_resource.excluded_members << "extra_user" allow(@new_resource).to receive(:append).and_return(true) - expect(@provider.compare_group).to be_false + expect(@provider.compare_group).to be_falsey end it "should return true if the append is true and excluded_members include an existing user" do @new_resource.members.each {|m| @new_resource.excluded_members << m } @new_resource.members.clear allow(@new_resource).to receive(:append).and_return(true) - expect(@provider.compare_group).to be_true + expect(@provider.compare_group).to be_truthy end end @@ -259,26 +259,26 @@ describe Chef::Provider::User do @new_resource.members << "user1" @new_resource.members << "user2" allow(@new_resource).to receive(:append).and_return true - expect(@provider.compare_group).to be_true + expect(@provider.compare_group).to be_truthy expect(@provider.change_desc).to eq([ "add missing member(s): user1, user2" ]) end it "should report that the group members will be overwritten if not appending" do @new_resource.members << "user1" allow(@new_resource).to receive(:append).and_return false - expect(@provider.compare_group).to be_true + expect(@provider.compare_group).to be_truthy expect(@provider.change_desc).to eq([ "replace group members with new list of members" ]) end it "should report the gid will be changed when it does not match" do allow(@current_resource).to receive(:gid).and_return("BADF00D") - expect(@provider.compare_group).to be_true + expect(@provider.compare_group).to be_truthy expect(@provider.change_desc).to eq([ "change gid #{@current_resource.gid} to #{@new_resource.gid}" ]) end it "should report no change reason when no change is required" do - expect(@provider.compare_group).to be_false + expect(@provider.compare_group).to be_falsey expect(@provider.change_desc).to eq([ ]) end end diff --git a/spec/unit/provider/ifconfig/debian_spec.rb b/spec/unit/provider/ifconfig/debian_spec.rb index 160a0ed4eb..351e734040 100644 --- a/spec/unit/provider/ifconfig/debian_spec.rb +++ b/spec/unit/provider/ifconfig/debian_spec.rb @@ -77,29 +77,29 @@ describe Chef::Provider::Ifconfig::Debian do context "when the interface_dot_d directory does not exist" do before do FileUtils.rmdir tempdir_path - expect(File.exists?(tempdir_path)).to be_false + expect(File.exists?(tempdir_path)).to be_falsey end it "should create the /etc/network/interfaces.d directory" do provider.run_action(:add) - expect(File.exists?(tempdir_path)).to be_true - expect(File.directory?(tempdir_path)).to be_true + expect(File.exists?(tempdir_path)).to be_truthy + expect(File.directory?(tempdir_path)).to be_truthy end it "should mark the resource as updated" do provider.run_action(:add) - expect(new_resource.updated_by_last_action?).to be_true + expect(new_resource.updated_by_last_action?).to be_truthy end end context "when the interface_dot_d directory exists" do before do - expect(File.exists?(tempdir_path)).to be_true + expect(File.exists?(tempdir_path)).to be_truthy end it "should still mark the resource as updated (we still write a file to it)" do provider.run_action(:add) - expect(new_resource.updated_by_last_action?).to be_true + expect(new_resource.updated_by_last_action?).to be_truthy end end end @@ -120,7 +120,7 @@ iface eth0 inet static netmask 255.255.254.0 EOF ) - expect(File.exists?(tempdir_path)).to be_true # since the file exists, the enclosing dir must also exist + expect(File.exists?(tempdir_path)).to be_truthy # since the file exists, the enclosing dir must also exist end context "when the /etc/network/interfaces file has the source line" do @@ -147,7 +147,7 @@ EOF it "should not mark the resource as updated" do provider.run_action(:add) pending "superclass ifconfig provider is not idempotent" - expect(new_resource.updated_by_last_action?).to be_false + expect(new_resource.updated_by_last_action?).to be_falsey end end @@ -175,7 +175,7 @@ EOF it "should mark the resource as updated" do provider.run_action(:add) - expect(new_resource.updated_by_last_action?).to be_true + expect(new_resource.updated_by_last_action?).to be_truthy end end end @@ -215,28 +215,28 @@ EOF context "when the interface_dot_d directory does not exist" do before do FileUtils.rmdir tempdir_path - expect(File.exists?(tempdir_path)).to be_false + expect(File.exists?(tempdir_path)).to be_falsey end it "should not create the /etc/network/interfaces.d directory" do provider.run_action(:add) - expect(File.exists?(tempdir_path)).not_to be_true + expect(File.exists?(tempdir_path)).not_to be_truthy end it "should mark the resource as updated" do provider.run_action(:add) - expect(new_resource.updated_by_last_action?).to be_true + expect(new_resource.updated_by_last_action?).to be_truthy end end context "when the interface_dot_d directory exists" do before do - expect(File.exists?(tempdir_path)).to be_true + expect(File.exists?(tempdir_path)).to be_truthy end it "should still mark the resource as updated (we still write a file to it)" do provider.run_action(:add) - expect(new_resource.updated_by_last_action?).to be_true + expect(new_resource.updated_by_last_action?).to be_truthy end end end @@ -258,7 +258,7 @@ iface eth0 inet static EOF ) expect(File).not_to receive(:new).with(config_filename_ifcfg, "w") - expect(File.exists?(tempdir_path)).to be_true # since the file exists, the enclosing dir must also exist + expect(File.exists?(tempdir_path)).to be_truthy # since the file exists, the enclosing dir must also exist end context "when the /etc/network/interfaces file has the source line" do @@ -283,7 +283,7 @@ another line it "should not mark the resource as updated" do provider.run_action(:add) pending "superclass ifconfig provider is not idempotent" - expect(new_resource.updated_by_last_action?).to be_false + expect(new_resource.updated_by_last_action?).to be_falsey end end @@ -308,7 +308,7 @@ source #{tempdir_path}/* it "should mark the resource as updated" do provider.run_action(:add) - expect(new_resource.updated_by_last_action?).to be_true + expect(new_resource.updated_by_last_action?).to be_truthy end end end @@ -345,9 +345,9 @@ source #{tempdir_path}/* # internal implementation detail of Ifconfig. expect_any_instance_of(Chef::Provider::File).to receive(:action_delete).and_call_original - expect(File.exist?(config_filename_ifcfg)).to be_true + expect(File.exist?(config_filename_ifcfg)).to be_truthy provider.run_action(:delete) - expect(File.exist?(config_filename_ifcfg)).to be_false + expect(File.exist?(config_filename_ifcfg)).to be_falsey end end diff --git a/spec/unit/provider/link_spec.rb b/spec/unit/provider/link_spec.rb index 3ae8a71cff..ab5b439eac 100644 --- a/spec/unit/provider/link_spec.rb +++ b/spec/unit/provider/link_spec.rb @@ -68,7 +68,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do expect(provider.current_resource.link_type).to eq(:symbolic) end it "should update the source of the existing link with the links target" do - expect(paths_eql?(provider.current_resource.to, "#{CHEF_SPEC_DATA}/fofile")).to be_true + expect(paths_eql?(provider.current_resource.to, "#{CHEF_SPEC_DATA}/fofile")).to be_truthy end it "should set the owner" do expect(provider.current_resource.owner).to eq(501) @@ -110,7 +110,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do expect(provider.current_resource.link_type).to eq(:symbolic) end it "should update the source of the existing link to the link's target" do - expect(paths_eql?(provider.current_resource.to, "#{CHEF_SPEC_DATA}/fofile")).to be_true + expect(paths_eql?(provider.current_resource.to, "#{CHEF_SPEC_DATA}/fofile")).to be_truthy end it "should not set the owner" do expect(provider.current_resource.owner).to be_nil @@ -221,7 +221,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do expect(provider.current_resource.link_type).to eq(:hard) end it "should update the source of the existing link to the link's target" do - expect(paths_eql?(provider.current_resource.to, "#{CHEF_SPEC_DATA}/fofile")).to be_true + expect(paths_eql?(provider.current_resource.to, "#{CHEF_SPEC_DATA}/fofile")).to be_truthy end it "should not set the owner" do expect(provider.current_resource.owner).to eq(nil) diff --git a/spec/unit/provider/mdadm_spec.rb b/spec/unit/provider/mdadm_spec.rb index ddff49da13..77ed5798a8 100644 --- a/spec/unit/provider/mdadm_spec.rb +++ b/spec/unit/provider/mdadm_spec.rb @@ -41,13 +41,13 @@ describe Chef::Provider::Mdadm do it "determines that the metadevice exists when mdadm exit code is zero" do allow(@provider).to receive(:shell_out!).with("mdadm --detail --test /dev/md1", :returns => [0,4]).and_return(OpenStruct.new(:status => 0)) @provider.load_current_resource - expect(@provider.current_resource.exists).to be_true + expect(@provider.current_resource.exists).to be_truthy end it "determines that the metadevice does not exist when mdadm exit code is 4" do allow(@provider).to receive(:shell_out!).with("mdadm --detail --test /dev/md1", :returns => [0,4]).and_return(OpenStruct.new(:status => 4)) @provider.load_current_resource - expect(@provider.current_resource.exists).to be_false + expect(@provider.current_resource.exists).to be_falsey end end diff --git a/spec/unit/provider/mount/aix_spec.rb b/spec/unit/provider/mount/aix_spec.rb index cdf4e0555d..ca0ddd006c 100644 --- a/spec/unit/provider/mount/aix_spec.rb +++ b/spec/unit/provider/mount/aix_spec.rb @@ -84,7 +84,7 @@ ENABLED stub_mounted_enabled(@provider, @mounted_output, "") @provider.load_current_resource - expect(@provider.current_resource.mounted).to be_true + expect(@provider.current_resource.mounted).to be_truthy end it "should set current_resource.mounted to false if device is not mounted" do @@ -92,7 +92,7 @@ ENABLED @provider.load_current_resource - expect(@provider.current_resource.mounted).to be_false + expect(@provider.current_resource.mounted).to be_falsey end it "should set current_resource.mounted to false if the mount point is used for another device" do @@ -100,7 +100,7 @@ ENABLED @provider.load_current_resource - expect(@provider.current_resource.mounted).to be_false + expect(@provider.current_resource.mounted).to be_falsey end end @@ -110,8 +110,8 @@ ENABLED @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_true - expect(@provider.current_resource.mounted).to be_true + expect(@provider.current_resource.enabled).to be_truthy + expect(@provider.current_resource.mounted).to be_truthy expect(@provider.current_resource.mount_point).to eql(@new_resource.mount_point) expect(@provider.current_resource.fstype).to eql("jfs2") expect(@provider.current_resource.options).to eql(['rw']) diff --git a/spec/unit/provider/mount/mount_spec.rb b/spec/unit/provider/mount/mount_spec.rb index 40cfbcaf39..7e9531a8ac 100644 --- a/spec/unit/provider/mount/mount_spec.rb +++ b/spec/unit/provider/mount/mount_spec.rb @@ -67,14 +67,14 @@ describe Chef::Provider::Mount::Mount do "cifs" => "//cifsserver/share" }.each do |type, fs_spec| it "should detect network fs_spec (#{type})" do @new_resource.device fs_spec - expect(@provider.network_device?).to be_true + expect(@provider.network_device?).to be_truthy end it "should ignore trailing slash and set mounted to true for network mount (#{type})" do @new_resource.device fs_spec allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "#{fs_spec}/ on /tmp/foo type #{type} (rw)\n")) @provider.load_current_resource - expect(@provider.current_resource.mounted).to be_true + expect(@provider.current_resource.mounted).to be_truthy end end end @@ -123,13 +123,13 @@ describe Chef::Provider::Mount::Mount do it "should set mounted true if the mount point is found in the mounts list" do allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "/dev/sdz1 on /tmp/foo type ext3 (rw)\n")) @provider.load_current_resource() - expect(@provider.current_resource.mounted).to be_true + expect(@provider.current_resource.mounted).to be_truthy end it "should set mounted false if another mount point beginning with the same path is found in the mounts list" do allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "/dev/sdz1 on /tmp/foobar type ext3 (rw)\n")) @provider.load_current_resource() - expect(@provider.current_resource.mounted).to be_false + expect(@provider.current_resource.mounted).to be_falsey end it "should set mounted true if the symlink target of the device is found in the mounts list" do @@ -141,7 +141,7 @@ describe Chef::Provider::Mount::Mount do allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "#{target} on /tmp/foo type ext3 (rw)\n")) @provider.load_current_resource() - expect(@provider.current_resource.mounted).to be_true + expect(@provider.current_resource.mounted).to be_truthy end it "should set mounted true if the symlink target of the device is relative and is found in the mounts list - CHEF-4957" do @@ -155,7 +155,7 @@ describe Chef::Provider::Mount::Mount do allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "#{absolute_target} on /tmp/foo type ext3 (rw)\n")) @provider.load_current_resource() - expect(@provider.current_resource.mounted).to be_true + expect(@provider.current_resource.mounted).to be_truthy end it "should set mounted true if the mount point is found last in the mounts list" do @@ -164,7 +164,7 @@ describe Chef::Provider::Mount::Mount do allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => mount)) @provider.load_current_resource() - expect(@provider.current_resource.mounted).to be_true + expect(@provider.current_resource.mounted).to be_truthy end it "should set mounted false if the mount point is not last in the mounts list" do @@ -173,13 +173,13 @@ describe Chef::Provider::Mount::Mount do allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => mount)) @provider.load_current_resource() - expect(@provider.current_resource.mounted).to be_false + expect(@provider.current_resource.mounted).to be_falsey end it "mounted should be false if the mount point is not found in the mounts list" do allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "/dev/sdy1 on /tmp/foo type ext3 (rw)\n")) @provider.load_current_resource() - expect(@provider.current_resource.mounted).to be_false + expect(@provider.current_resource.mounted).to be_falsey end it "should set enabled to true if the mount point is last in fstab" do @@ -189,7 +189,7 @@ describe Chef::Provider::Mount::Mount do allow(::File).to receive(:foreach).with("/etc/fstab").and_yield(fstab1).and_yield(fstab2) @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_true + expect(@provider.current_resource.enabled).to be_truthy end it "should set enabled to true if the mount point is not last in fstab and mount_point is a substring of another mount" do @@ -199,7 +199,7 @@ describe Chef::Provider::Mount::Mount do allow(::File).to receive(:foreach).with("/etc/fstab").and_yield(fstab1).and_yield(fstab2) @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_true + expect(@provider.current_resource.enabled).to be_truthy end it "should set enabled to true if the symlink target is in fstab" do @@ -213,7 +213,7 @@ describe Chef::Provider::Mount::Mount do allow(::File).to receive(:foreach).with("/etc/fstab").and_yield fstab @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_true + expect(@provider.current_resource.enabled).to be_truthy end it "should set enabled to true if the symlink target is relative and is in fstab - CHEF-4957" do @@ -227,7 +227,7 @@ describe Chef::Provider::Mount::Mount do allow(::File).to receive(:foreach).with("/etc/fstab").and_yield fstab @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_true + expect(@provider.current_resource.enabled).to be_truthy end it "should set enabled to false if the mount point is not in fstab" do @@ -235,7 +235,7 @@ describe Chef::Provider::Mount::Mount do allow(::File).to receive(:foreach).with("/etc/fstab").and_yield fstab @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_false + expect(@provider.current_resource.enabled).to be_falsey end it "should ignore commented lines in fstab " do @@ -243,7 +243,7 @@ describe Chef::Provider::Mount::Mount do allow(::File).to receive(:foreach).with("/etc/fstab").and_yield fstab @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_false + expect(@provider.current_resource.enabled).to be_falsey end it "should set enabled to false if the mount point is not last in fstab" do @@ -252,7 +252,7 @@ describe Chef::Provider::Mount::Mount do allow(::File).to receive(:foreach).with("/etc/fstab").and_yield(line_1).and_yield(line_2) @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_false + expect(@provider.current_resource.enabled).to be_falsey end it "should not mangle the mount options if the device in fstab is a symlink" do diff --git a/spec/unit/provider/mount/solaris_spec.rb b/spec/unit/provider/mount/solaris_spec.rb index 93321a8ad6..9a9b09b531 100644 --- a/spec/unit/provider/mount/solaris_spec.rb +++ b/spec/unit/provider/mount/solaris_spec.rb @@ -180,11 +180,11 @@ describe Chef::Provider::Mount::Solaris, :unix_only do end it "should set the mounted status on the current_resource" do - expect(provider.current_resource.mounted).to be_true + expect(provider.current_resource.mounted).to be_truthy end it "should set the enabled status on the current_resource" do - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end it "should set the fstype field on the current_resource" do @@ -258,7 +258,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do let(:fsck_device) { "-" } it "should work at some point in the future" do - pending "SMBFS mounts on solaris look like they will need some future code work and more investigation" + skip "SMBFS mounts on solaris look like they will need some future code work and more investigation" end end @@ -304,11 +304,11 @@ describe Chef::Provider::Mount::Solaris, :unix_only do end it "should set the mounted status on the current_resource" do - expect(provider.current_resource.mounted).to be_true + expect(provider.current_resource.mounted).to be_truthy end it "should set the enabled status on the current_resource" do - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end it "should set the fstype field on the current_resource" do @@ -322,7 +322,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do it "should set the pass field on the current_resource" do # is this correct or should it be nil? # - # vfstab man page says. + # vfstab man page says. # "A - is used to indicate no entry in a field." # 0 and - could mean different things for some file systems expect(provider.current_resource.pass).to eql(0) @@ -354,11 +354,11 @@ describe Chef::Provider::Mount::Solaris, :unix_only do end it "should set mounted true if the symlink target of the device is found in the mounts list" do - expect(provider.current_resource.mounted).to be_true + expect(provider.current_resource.mounted).to be_truthy end it "should set enabled true if the symlink target of the device is found in the vfstab" do - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end it "should have the correct mount options" do @@ -391,11 +391,11 @@ describe Chef::Provider::Mount::Solaris, :unix_only do end it "should set mounted true if the symlink target of the device is found in the mounts list" do - expect(provider.current_resource.mounted).to be_true + expect(provider.current_resource.mounted).to be_truthy end it "should set enabled true if the symlink target of the device is found in the vfstab" do - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end it "should have the correct mount options" do @@ -412,7 +412,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do } it "should set mounted true" do provider.load_current_resource() - expect(provider.current_resource.mounted).to be_true + expect(provider.current_resource.mounted).to be_truthy end end @@ -425,7 +425,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do } it "should set mounted false" do provider.load_current_resource() - expect(provider.current_resource.mounted).to be_false + expect(provider.current_resource.mounted).to be_falsey end end @@ -437,7 +437,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do } it "should set mounted false" do provider.load_current_resource() - expect(provider.current_resource.mounted).to be_false + expect(provider.current_resource.mounted).to be_falsey end end @@ -449,7 +449,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do } it "should set mounted false" do provider.load_current_resource() - expect(provider.current_resource.mounted).to be_false + expect(provider.current_resource.mounted).to be_falsey end end @@ -463,7 +463,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do it "should set enabled to true" do provider.load_current_resource - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end end @@ -477,7 +477,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do it "should set enabled to true" do provider.load_current_resource - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end end @@ -491,7 +491,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do it "should set enabled to false" do provider.load_current_resource - expect(provider.current_resource.enabled).to be_false + expect(provider.current_resource.enabled).to be_falsey end end @@ -504,7 +504,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do it "should set enabled to false" do provider.load_current_resource - expect(provider.current_resource.enabled).to be_false + expect(provider.current_resource.enabled).to be_falsey end end @@ -517,7 +517,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do it "should set enabled to false" do provider.load_current_resource - expect(provider.current_resource.enabled).to be_false + expect(provider.current_resource.enabled).to be_falsey end end @@ -530,7 +530,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do it "should set enabled to false" do provider.load_current_resource - expect(provider.current_resource.enabled).to be_false + expect(provider.current_resource.enabled).to be_falsey end end end diff --git a/spec/unit/provider/package/freebsd/pkgng_spec.rb b/spec/unit/provider/package/freebsd/pkgng_spec.rb index d314735bf0..0c1e89c7ab 100644 --- a/spec/unit/provider/package/freebsd/pkgng_spec.rb +++ b/spec/unit/provider/package/freebsd/pkgng_spec.rb @@ -33,7 +33,7 @@ describe Chef::Provider::Package::Freebsd::Port do describe "initialization" do it "should create a current resource with the name of the new resource" do - expect(@provider.current_resource.is_a?(Chef::Resource::Package)).to be_true + expect(@provider.current_resource.is_a?(Chef::Resource::Package)).to be_truthy expect(@provider.current_resource.name).to eq('zsh') end end diff --git a/spec/unit/provider/package/freebsd/port_spec.rb b/spec/unit/provider/package/freebsd/port_spec.rb index 3085b16a92..2e32e88f97 100644 --- a/spec/unit/provider/package/freebsd/port_spec.rb +++ b/spec/unit/provider/package/freebsd/port_spec.rb @@ -33,7 +33,7 @@ describe Chef::Provider::Package::Freebsd::Port do describe "initialization" do it "should create a current resource with the name of the new resource" do - expect(@provider.current_resource.is_a?(Chef::Resource::Package)).to be_true + expect(@provider.current_resource.is_a?(Chef::Resource::Package)).to be_truthy expect(@provider.current_resource.name).to eq('zsh') end end diff --git a/spec/unit/provider/package/rubygems_spec.rb b/spec/unit/provider/package/rubygems_spec.rb index bce0054220..db1c21090d 100644 --- a/spec/unit/provider/package/rubygems_spec.rb +++ b/spec/unit/provider/package/rubygems_spec.rb @@ -121,6 +121,7 @@ describe Chef::Provider::Package::Rubygems::CurrentGemEnvironment do Gem.const_set(:Format, Object.new) @remove_gem_format = true end + allow(Gem::Package).to receive(:respond_to?).and_call_original allow(Gem::Package).to receive(:respond_to?).with(:open).and_return(false) end @@ -378,7 +379,7 @@ describe Chef::Provider::Package::Rubygems do it "target_version_already_installed? should return false so that we can search for candidates" do @provider.load_current_resource - expect(@provider.target_version_already_installed?).to be_false + expect(@provider.target_version_already_installed?).to be_falsey end end @@ -495,20 +496,20 @@ describe Chef::Provider::Package::Rubygems do describe "in the current gem environment" do it "installs the gem via the gems api when no explicit options are used" do expect(@provider.gem_env).to receive(:install).with(@gem_dep, :sources => nil) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end it "installs the gem via the gems api when a remote source is provided" do @new_resource.source('http://gems.example.org') sources = ['http://gems.example.org'] expect(@provider.gem_env).to receive(:install).with(@gem_dep, :sources => sources) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end it "installs the gem from file via the gems api when no explicit options are used" do @new_resource.source(CHEF_SPEC_DATA + '/gems/chef-integration-test-0.1.0.gem') expect(@provider.gem_env).to receive(:install).with(CHEF_SPEC_DATA + '/gems/chef-integration-test-0.1.0.gem') - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end it "installs the gem from file via the gems api when the package is a path and the source is nil" do @@ -517,7 +518,7 @@ describe Chef::Provider::Package::Rubygems do @provider.current_resource = @current_resource expect(@new_resource.source).to eq(CHEF_SPEC_DATA + '/gems/chef-integration-test-0.1.0.gem') expect(@provider.gem_env).to receive(:install).with(CHEF_SPEC_DATA + '/gems/chef-integration-test-0.1.0.gem') - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end # this catches 'gem_package "foo"' when "./foo" is a file in the cwd, and instead of installing './foo' it fetches the remote gem @@ -525,20 +526,20 @@ describe Chef::Provider::Package::Rubygems do allow(::File).to receive(:exists?).and_return(true) @new_resource.package_name('rspec-core') expect(@provider.gem_env).to receive(:install).with(@gem_dep, :sources => nil) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end it "installs the gem by shelling out when options are provided as a String" do @new_resource.options('-i /alt/install/location') expected ="gem install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\" -i /alt/install/location" expect(@provider).to receive(:shell_out!).with(expected, :env => nil) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end it "installs the gem via the gems api when options are given as a Hash" do @new_resource.options(:install_dir => '/alt/install/location') expect(@provider.gem_env).to receive(:install).with(@gem_dep, :sources => nil, :install_dir => '/alt/install/location') - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end describe "at a specific version" do @@ -548,7 +549,7 @@ describe Chef::Provider::Package::Rubygems do it "installs the gem via the gems api" do expect(@provider.gem_env).to receive(:install).with(@gem_dep, :sources => nil) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end end describe "at version specified with comparison operator" do @@ -574,7 +575,7 @@ describe Chef::Provider::Package::Rubygems do it "installs the gem by shelling out to gem install" do @new_resource.gem_binary('/usr/weird/bin/gem') expect(@provider).to receive(:shell_out!).with("/usr/weird/bin/gem install rspec-core -q --no-rdoc --no-ri -v \"#{@spec_version}\"", :env=>nil) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end it "installs the gem from file by shelling out to gem install" do @@ -582,7 +583,7 @@ describe Chef::Provider::Package::Rubygems do @new_resource.source(CHEF_SPEC_DATA + '/gems/chef-integration-test-0.1.0.gem') @new_resource.version('>= 0') expect(@provider).to receive(:shell_out!).with("/usr/weird/bin/gem install #{CHEF_SPEC_DATA}/gems/chef-integration-test-0.1.0.gem -q --no-rdoc --no-ri -v \">= 0\"", :env=>nil) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end it "installs the gem from file by shelling out to gem install when the package is a path and the source is nil" do @@ -593,7 +594,7 @@ describe Chef::Provider::Package::Rubygems do @new_resource.version('>= 0') expect(@new_resource.source).to eq(CHEF_SPEC_DATA + '/gems/chef-integration-test-0.1.0.gem') expect(@provider).to receive(:shell_out!).with("/usr/weird/bin/gem install #{CHEF_SPEC_DATA}/gems/chef-integration-test-0.1.0.gem -q --no-rdoc --no-ri -v \">= 0\"", :env=>nil) - expect(@provider.action_install).to be_true + expect(@provider.action_install).to be_truthy end end diff --git a/spec/unit/provider/package_spec.rb b/spec/unit/provider/package_spec.rb index 3a42bcacf6..2aeaf717e6 100644 --- a/spec/unit/provider/package_spec.rb +++ b/spec/unit/provider/package_spec.rb @@ -376,7 +376,7 @@ describe Chef::Provider::Package do end it "should never back up the cached response file" do - expect(@provider.preseed_resource('java', '6').backup).to be_false + expect(@provider.preseed_resource('java', '6').backup).to be_falsey end it "sets the install path of the resource to $file_cache/$cookbook/$pkg_name-$pkg_version.seed" do diff --git a/spec/unit/provider/remote_directory_spec.rb b/spec/unit/provider/remote_directory_spec.rb index a2f5092f57..4434714ebc 100644 --- a/spec/unit/provider/remote_directory_spec.rb +++ b/spec/unit/provider/remote_directory_spec.rb @@ -84,7 +84,7 @@ describe Chef::Provider::RemoteDirectory do expect(directory_resource.mode).to eq("0750") expect(directory_resource.group).to eq("wheel") expect(directory_resource.owner).to eq("root") - expect(directory_resource.recursive).to be_true + expect(directory_resource.recursive).to be_truthy end it "configures access control on files in the directory" do @@ -116,17 +116,17 @@ describe Chef::Provider::RemoteDirectory do it "creates the toplevel directory without error " do @resource.recursive(false) @provider.run_action(:create) - expect(::File.exist?(@destination_dir)).to be_true + expect(::File.exist?(@destination_dir)).to be_truthy end it "transfers the directory with all contents" do @provider.run_action(:create) - expect(::File.exist?(@destination_dir + '/remote_dir_file1.txt')).to be_true - expect(::File.exist?(@destination_dir + '/remote_dir_file2.txt')).to be_true - expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')).to be_true - expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file2.txt')).to be_true - expect(::File.exist?(@destination_dir + '/remotesubdir/.a_dotfile')).to be_true - expect(::File.exist?(@destination_dir + '/.a_dotdir/.a_dotfile_in_a_dotdir')).to be_true + expect(::File.exist?(@destination_dir + '/remote_dir_file1.txt')).to be_truthy + expect(::File.exist?(@destination_dir + '/remote_dir_file2.txt')).to be_truthy + expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')).to be_truthy + expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file2.txt')).to be_truthy + expect(::File.exist?(@destination_dir + '/remotesubdir/.a_dotfile')).to be_truthy + expect(::File.exist?(@destination_dir + '/.a_dotdir/.a_dotfile_in_a_dotdir')).to be_truthy end describe "only if it is missing" do @@ -141,8 +141,8 @@ describe Chef::Provider::RemoteDirectory do @provider.run_action(:create_if_missing) - expect(file1md5.eql?(Digest::MD5.hexdigest(File.read(@destination_dir + '/remote_dir_file1.txt')))).to be_true - expect(subdirfile1md5.eql?(Digest::MD5.hexdigest(File.read(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')))).to be_true + expect(file1md5.eql?(Digest::MD5.hexdigest(File.read(@destination_dir + '/remote_dir_file1.txt')))).to be_truthy + expect(subdirfile1md5.eql?(Digest::MD5.hexdigest(File.read(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')))).to be_truthy end end @@ -155,13 +155,13 @@ describe Chef::Provider::RemoteDirectory do FileUtils.touch(@destination_dir + '/remotesubdir/marked_for_death_again.txt') @provider.run_action(:create) - expect(::File.exist?(@destination_dir + '/remote_dir_file1.txt')).to be_true - expect(::File.exist?(@destination_dir + '/remote_dir_file2.txt')).to be_true - expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')).to be_true - expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file2.txt')).to be_true + expect(::File.exist?(@destination_dir + '/remote_dir_file1.txt')).to be_truthy + expect(::File.exist?(@destination_dir + '/remote_dir_file2.txt')).to be_truthy + expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')).to be_truthy + expect(::File.exist?(@destination_dir + '/remotesubdir/remote_subdir_file2.txt')).to be_truthy - expect(::File.exist?(@destination_dir + '/marked_for_death.txt')).to be_false - expect(::File.exist?(@destination_dir + '/remotesubdir/marked_for_death_again.txt')).to be_false + expect(::File.exist?(@destination_dir + '/marked_for_death.txt')).to be_falsey + expect(::File.exist?(@destination_dir + '/remotesubdir/marked_for_death_again.txt')).to be_falsey end it "removes files in subdirectories before files above" do @@ -172,10 +172,10 @@ describe Chef::Provider::RemoteDirectory do FileUtils.touch(@destination_dir + '/a/multiply/nested/baz.txt') FileUtils.touch(@destination_dir + '/a/multiply/nested/directory/qux.txt') @provider.run_action(:create) - expect(::File.exist?(@destination_dir + '/a/foo.txt')).to be_false - expect(::File.exist?(@destination_dir + '/a/multiply/bar.txt')).to be_false - expect(::File.exist?(@destination_dir + '/a/multiply/nested/baz.txt')).to be_false - expect(::File.exist?(@destination_dir + '/a/multiply/nested/directory/qux.txt')).to be_false + expect(::File.exist?(@destination_dir + '/a/foo.txt')).to be_falsey + expect(::File.exist?(@destination_dir + '/a/multiply/bar.txt')).to be_falsey + expect(::File.exist?(@destination_dir + '/a/multiply/nested/baz.txt')).to be_falsey + expect(::File.exist?(@destination_dir + '/a/multiply/nested/directory/qux.txt')).to be_falsey end it "removes directory symlinks properly", :not_supported_on_win2k3 do @@ -188,12 +188,12 @@ describe Chef::Provider::RemoteDirectory do Dir.mktmpdir do |tmp_dir| begin @fclass.file_class.symlink(tmp_dir.dup, symlinked_dir_path) - expect(::File.exist?(symlinked_dir_path)).to be_true + expect(::File.exist?(symlinked_dir_path)).to be_truthy @provider.run_action - expect(::File.exist?(symlinked_dir_path)).to be_false - expect(::File.exist?(tmp_dir)).to be_true + expect(::File.exist?(symlinked_dir_path)).to be_falsey + expect(::File.exist?(tmp_dir)).to be_truthy rescue Chef::Exceptions::Win32APIError => e pending "This must be run as an Administrator to create symlinks" end @@ -212,8 +212,8 @@ describe Chef::Provider::RemoteDirectory do file1md5 = Digest::MD5.hexdigest(::File.read(@destination_dir + '/remote_dir_file1.txt')) subdirfile1md5 = Digest::MD5.hexdigest(::File.read(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')) @provider.run_action(:create) - expect(file1md5.eql?(Digest::MD5.hexdigest(::File.read(@destination_dir + '/remote_dir_file1.txt')))).to be_true - expect(subdirfile1md5.eql?(Digest::MD5.hexdigest(::File.read(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')))).to be_true + expect(file1md5.eql?(Digest::MD5.hexdigest(::File.read(@destination_dir + '/remote_dir_file1.txt')))).to be_truthy + expect(subdirfile1md5.eql?(Digest::MD5.hexdigest(::File.read(@destination_dir + '/remotesubdir/remote_subdir_file1.txt')))).to be_truthy end end diff --git a/spec/unit/provider/remote_file/ftp_spec.rb b/spec/unit/provider/remote_file/ftp_spec.rb index b3a3fcf376..dbbddd8e84 100644 --- a/spec/unit/provider/remote_file/ftp_spec.rb +++ b/spec/unit/provider/remote_file/ftp_spec.rb @@ -60,7 +60,7 @@ describe Chef::Provider::RemoteFile::FTP do let(:uri) { URI.parse("ftp://opscode.com/seattle.txt") } before(:each) do - allow(Net::FTP).to receive(:new).with().and_return(ftp) + allow(Net::FTP).to receive(:new).with(no_args).and_return(ftp) allow(Tempfile).to receive(:new).and_return(tempfile) end @@ -89,13 +89,13 @@ describe Chef::Provider::RemoteFile::FTP do it "does not use passive mode when new_resource sets ftp_active_mode to true" do new_resource.ftp_active_mode(true) fetcher = Chef::Provider::RemoteFile::FTP.new(uri, new_resource, current_resource) - expect(fetcher.use_passive_mode?).to be_false + expect(fetcher.use_passive_mode?).to be_falsey end it "uses passive mode when new_resource sets ftp_active_mode to false" do new_resource.ftp_active_mode(false) fetcher = Chef::Provider::RemoteFile::FTP.new(uri, new_resource, current_resource) - expect(fetcher.use_passive_mode?).to be_true + expect(fetcher.use_passive_mode?).to be_truthy end end diff --git a/spec/unit/provider/route_spec.rb b/spec/unit/provider/route_spec.rb index e63029ad07..ff68eea895 100644 --- a/spec/unit/provider/route_spec.rb +++ b/spec/unit/provider/route_spec.rb @@ -65,7 +65,7 @@ describe Chef::Provider::Route do provider = Chef::Provider::Route.new(resource, @run_context) provider.load_current_resource - expect(provider.is_running).to be_false + expect(provider.is_running).to be_falsey end it "should detect existing routes and set is_running attribute correctly" do @@ -75,7 +75,7 @@ describe Chef::Provider::Route do provider = Chef::Provider::Route.new(resource, @run_context) provider.load_current_resource - expect(provider.is_running).to be_true + expect(provider.is_running).to be_truthy end it "should use gateway value when matching routes" do @@ -85,7 +85,7 @@ describe Chef::Provider::Route do provider = Chef::Provider::Route.new(resource, @run_context) provider.load_current_resource - expect(provider.is_running).to be_false + expect(provider.is_running).to be_falsey end end end diff --git a/spec/unit/provider/script_spec.rb b/spec/unit/provider/script_spec.rb index 7dc8588397..4979475b79 100644 --- a/spec/unit/provider/script_spec.rb +++ b/spec/unit/provider/script_spec.rb @@ -42,7 +42,7 @@ describe Chef::Provider::Script, "action_run" do it "unlinks the tempfile when finished" do tempfile_path = @provider.script_file.path @provider.unlink_script_file - expect(File.exist?(tempfile_path)).to be_false + expect(File.exist?(tempfile_path)).to be_falsey end it "sets the owner and group for the script file" do diff --git a/spec/unit/provider/service/aix_service_spec.rb b/spec/unit/provider/service/aix_service_spec.rb index a2557354c2..796661145b 100644 --- a/spec/unit/provider/service/aix_service_spec.rb +++ b/spec/unit/provider/service/aix_service_spec.rb @@ -55,7 +55,7 @@ describe Chef::Provider::Service::Aix do expect(@provider).to receive(:is_resource_group?).with(["chef chef 12345 active"]) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end end @@ -69,7 +69,7 @@ describe Chef::Provider::Service::Aix do expect(@provider).to receive(:is_resource_group?).with(["chef chef inoperative"]) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end end end @@ -83,7 +83,7 @@ describe Chef::Provider::Service::Aix do it "service is a group" do expect(@provider).to receive(:shell_out!).with("lssrc -a | grep -w chef").and_return(@status) @provider.load_current_resource - expect(@provider.instance_eval("@is_resource_group")).to be_true + expect(@provider.instance_eval("@is_resource_group")).to be_truthy end end @@ -95,7 +95,7 @@ describe Chef::Provider::Service::Aix do it "service is a group" do expect(@provider).to receive(:shell_out!).with("lssrc -a | grep -w chef").and_return(@status) @provider.load_current_resource - expect(@provider.instance_eval("@is_resource_group")).to be_true + expect(@provider.instance_eval("@is_resource_group")).to be_truthy end end @@ -107,7 +107,7 @@ describe Chef::Provider::Service::Aix do it "service is a subsystem" do expect(@provider).to receive(:shell_out!).with("lssrc -a | grep -w chef").and_return(@status) @provider.load_current_resource - expect(@provider.instance_eval("@is_resource_group")).to be_false + expect(@provider.instance_eval("@is_resource_group")).to be_falsey end end end diff --git a/spec/unit/provider/service/arch_service_spec.rb b/spec/unit/provider/service/arch_service_spec.rb index e71d9adfad..49be0e274c 100644 --- a/spec/unit/provider/service/arch_service_spec.rb +++ b/spec/unit/provider/service/arch_service_spec.rb @@ -62,19 +62,19 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do it "should set running to true if the status command returns 0" do allow(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 0)) @provider.load_current_resource - expect(@provider.current_resource.running).to be_true + expect(@provider.current_resource.running).to be_truthy end it "should set running to false if the status command returns anything except 0" do allow(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 1)) @provider.load_current_resource - expect(@provider.current_resource.running).to be_false + expect(@provider.current_resource.running).to be_falsey end it "should set running to false if the status command raises" do allow(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_raise(Mixlib::ShellOut::ShellCommandFailed) @provider.load_current_resource - expect(@provider.current_resource.running).to be_false + expect(@provider.current_resource.running).to be_falsey end end @@ -135,13 +135,13 @@ aj 7842 5057 0 21:26 pts/2 00:00:06 poos RUNNING_PS allow(@status).to receive(:stdout).and_return(@stdout) @provider.load_current_resource - expect(@provider.current_resource.running).to be_true + expect(@provider.current_resource.running).to be_truthy end it "determines the service is not running when it does not appear in ps" do allow(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@provider.current_resource.running).to be_false + expect(@provider.current_resource.running).to be_falsey end it "should raise an exception if ps fails" do diff --git a/spec/unit/provider/service/debian_service_spec.rb b/spec/unit/provider/service/debian_service_spec.rb index b974a6bf9e..a4667e8ce8 100644 --- a/spec/unit/provider/service/debian_service_spec.rb +++ b/spec/unit/provider/service/debian_service_spec.rb @@ -67,13 +67,13 @@ describe Chef::Provider::Service::Debian do end it "says the service is enabled" do - expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_true + expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_truthy end it "stores the 'enabled' state" do allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource) expect(@provider.load_current_resource).to equal(@current_resource) - expect(@current_resource.enabled).to be_true + expect(@current_resource.enabled).to be_truthy end end @@ -90,13 +90,13 @@ describe Chef::Provider::Service::Debian do end it "says the service is disabled" do - expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_false + expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_falsey end it "stores the 'disabled' state" do allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource) expect(@provider.load_current_resource).to equal(@current_resource) - expect(@current_resource.enabled).to be_false + expect(@current_resource.enabled).to be_falsey end end @@ -206,13 +206,13 @@ insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop end it "says the service is enabled" do - expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_true + expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_truthy end it "stores the 'enabled' state" do allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource) expect(@provider.load_current_resource).to equal(@current_resource) - expect(@current_resource.enabled).to be_true + expect(@current_resource.enabled).to be_truthy end it "stores the start/stop priorities of the service" do @@ -232,13 +232,13 @@ insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop end it "says the service is disabled" do - expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_false + expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_falsey end it "stores the 'disabled' state" do allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource) expect(@provider.load_current_resource).to equal(@current_resource) - expect(@current_resource.enabled).to be_false + expect(@current_resource.enabled).to be_falsey end end end diff --git a/spec/unit/provider/service/freebsd_service_spec.rb b/spec/unit/provider/service/freebsd_service_spec.rb index eb55fac820..91d2d8e063 100644 --- a/spec/unit/provider/service/freebsd_service_spec.rb +++ b/spec/unit/provider/service/freebsd_service_spec.rb @@ -172,14 +172,14 @@ PS_SAMPLE it "should set running to true" do allow(provider).to receive(:shell_out!).and_return(status) provider.determine_current_status! - expect(current_resource.running).to be_true + expect(current_resource.running).to be_truthy end end it "should set running to false if the regex doesn't match" do allow(provider).to receive(:shell_out!).and_return(status) provider.determine_current_status! - expect(current_resource.running).to be_false + expect(current_resource.running).to be_falsey end it "should set running to nil if ps fails" do diff --git a/spec/unit/provider/service/gentoo_service_spec.rb b/spec/unit/provider/service/gentoo_service_spec.rb index 04734e9c5d..c08982acc3 100644 --- a/spec/unit/provider/service/gentoo_service_spec.rb +++ b/spec/unit/provider/service/gentoo_service_spec.rb @@ -48,13 +48,13 @@ describe Chef::Provider::Service::Gentoo do it "should track when service file is not found in /etc/runlevels" do @provider.load_current_resource - expect(@provider.instance_variable_get("@found_script")).to be_false + expect(@provider.instance_variable_get("@found_script")).to be_falsey end it "should track when service file is found in /etc/runlevels/**/" do allow(Dir).to receive(:glob).with("/etc/runlevels/**/chef").and_return(["/etc/runlevels/default/chef"]) @provider.load_current_resource - expect(@provider.instance_variable_get("@found_script")).to be_true + expect(@provider.instance_variable_get("@found_script")).to be_truthy end describe "when detecting the service enable state" do @@ -70,7 +70,7 @@ describe Chef::Provider::Service::Gentoo do end it "should set enabled to true" do @provider.load_current_resource - expect(@current_resource.enabled).to be_true + expect(@current_resource.enabled).to be_truthy end end @@ -82,7 +82,7 @@ describe Chef::Provider::Service::Gentoo do it "should set enabled to false" do @provider.load_current_resource - expect(@current_resource.enabled).to be_false + expect(@current_resource.enabled).to be_falsey end end @@ -94,7 +94,7 @@ describe Chef::Provider::Service::Gentoo do it "should set enabled to false" do @provider.load_current_resource - expect(@current_resource.enabled).to be_false + expect(@current_resource.enabled).to be_falsey end end @@ -108,17 +108,17 @@ describe Chef::Provider::Service::Gentoo do it "should support the status command automatically" do @provider.load_current_resource - expect(@new_resource.supports[:status]).to be_true + expect(@new_resource.supports[:status]).to be_truthy end it "should support the restart command automatically" do @provider.load_current_resource - expect(@new_resource.supports[:restart]).to be_true + expect(@new_resource.supports[:restart]).to be_truthy end it "should not support the reload command automatically" do @provider.load_current_resource - expect(@new_resource.supports[:reload]).not_to be_true + expect(@new_resource.supports[:reload]).not_to be_truthy end end diff --git a/spec/unit/provider/service/init_service_spec.rb b/spec/unit/provider/service/init_service_spec.rb index 5dc5256061..827a4261e1 100644 --- a/spec/unit/provider/service/init_service_spec.rb +++ b/spec/unit/provider/service/init_service_spec.rb @@ -64,20 +64,20 @@ PS it "should set running to true if the status command returns 0" do allow(@provider).to receive(:shell_out).with("/etc/init.d/#{@current_resource.service_name} status").and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end it "should set running to false if the status command returns anything except 0" do allow(@status).to receive(:exitstatus).and_return(1) allow(@provider).to receive(:shell_out).with("/etc/init.d/#{@current_resource.service_name} status").and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end it "should set running to false if the status command raises" do allow(@provider).to receive(:shell_out).and_raise(Mixlib::ShellOut::ShellCommandFailed) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end end @@ -139,13 +139,13 @@ aj 7842 5057 0 21:26 pts/2 00:00:06 poos RUNNING_PS allow(@status).to receive(:stdout).and_return(@stdout) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end it "should set running to false if the regex doesn't match" do allow(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end it "should raise an exception if ps fails" do diff --git a/spec/unit/provider/service/insserv_service_spec.rb b/spec/unit/provider/service/insserv_service_spec.rb index 6cead238fe..3799daebb4 100644 --- a/spec/unit/provider/service/insserv_service_spec.rb +++ b/spec/unit/provider/service/insserv_service_spec.rb @@ -41,7 +41,7 @@ describe Chef::Provider::Service::Insserv do it "sets the current enabled status to true" do @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_true + expect(@provider.current_resource.enabled).to be_truthy end end @@ -52,7 +52,7 @@ describe Chef::Provider::Service::Insserv do it "sets the current enabled status to false" do @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_false + expect(@provider.current_resource.enabled).to be_falsey end end diff --git a/spec/unit/provider/service/invokercd_service_spec.rb b/spec/unit/provider/service/invokercd_service_spec.rb index 0b3b799798..81588c80e5 100644 --- a/spec/unit/provider/service/invokercd_service_spec.rb +++ b/spec/unit/provider/service/invokercd_service_spec.rb @@ -64,20 +64,20 @@ PS it "should set running to true if the status command returns 0" do allow(@provider).to receive(:shell_out).with("/usr/sbin/invoke-rc.d #{@current_resource.service_name} status").and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end it "should set running to false if the status command returns anything except 0" do allow(@status).to receive(:exitstatus).and_return(1) allow(@provider).to receive(:shell_out).with("/usr/sbin/invoke-rc.d #{@current_resource.service_name} status").and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end it "should set running to false if the status command raises" do allow(@provider).to receive(:shell_out).with("/usr/sbin/invoke-rc.d #{@current_resource.service_name} status").and_raise(Mixlib::ShellOut::ShellCommandFailed) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end end @@ -125,14 +125,14 @@ RUNNING_PS @status = double("Status", :exitstatus => 0, :stdout => @stdout) expect(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end it "should set running to false if the regex doesn't match" do @status = double("Status", :exitstatus => 0, :stdout => @stdout) expect(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end it "should raise an exception if ps fails" do diff --git a/spec/unit/provider/service/macosx_spec.rb b/spec/unit/provider/service/macosx_spec.rb index 0d31ae2ffb..fb751592df 100644 --- a/spec/unit/provider/service/macosx_spec.rb +++ b/spec/unit/provider/service/macosx_spec.rb @@ -130,11 +130,11 @@ XML end it "sets resource running state to true" do - expect(provider.current_resource.running).to be_true + expect(provider.current_resource.running).to be_truthy end it "sets resouce enabled state to true" do - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end end @@ -164,11 +164,11 @@ SVC_LIST end it "sets resource running state to false" do - expect(provider.current_resource.running).to be_false + expect(provider.current_resource.running).to be_falsey end it "sets resouce enabled state to true" do - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end end @@ -180,7 +180,7 @@ SVC_LIST it "sets service running state to false" do provider.load_current_resource - expect(provider.current_resource.running).to be_false + expect(provider.current_resource.running).to be_falsey end context "and plist for service is not available" do @@ -190,7 +190,7 @@ SVC_LIST end it "sets resouce enabled state to false" do - expect(provider.current_resource.enabled).to be_false + expect(provider.current_resource.enabled).to be_falsey end end @@ -201,7 +201,7 @@ SVC_LIST end it "sets resouce enabled state to true" do - expect(provider.current_resource.enabled).to be_true + expect(provider.current_resource.enabled).to be_truthy end end diff --git a/spec/unit/provider/service/redhat_spec.rb b/spec/unit/provider/service/redhat_spec.rb index ed3dd5bfa7..73cfec8a6f 100644 --- a/spec/unit/provider/service/redhat_spec.rb +++ b/spec/unit/provider/service/redhat_spec.rb @@ -69,9 +69,9 @@ describe "Chef::Provider::Service::Redhat" do expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:on 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) - expect(@provider.instance_variable_get("@service_missing")).to be_false + expect(@provider.instance_variable_get("@service_missing")).to be_falsey @provider.load_current_resource - expect(@current_resource.enabled).to be_true + expect(@current_resource.enabled).to be_truthy end it "sets the current enabled status to false if the regex does not match" do @@ -79,9 +79,9 @@ describe "Chef::Provider::Service::Redhat" do expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:off 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) - expect(@provider.instance_variable_get("@service_missing")).to be_false + expect(@provider.instance_variable_get("@service_missing")).to be_falsey expect(@provider.load_current_resource).to eql(@current_resource) - expect(@current_resource.enabled).to be_false + expect(@current_resource.enabled).to be_falsey end end diff --git a/spec/unit/provider/service/simple_service_spec.rb b/spec/unit/provider/service/simple_service_spec.rb index 83ebcb688f..895c559dff 100644 --- a/spec/unit/provider/service/simple_service_spec.rb +++ b/spec/unit/provider/service/simple_service_spec.rb @@ -82,13 +82,13 @@ NOMOCKINGSTRINGSPLZ @status = double("Status", :exitstatus => 0, :stdout => @stdout) allow(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end it "should set running to false if the regex doesn't match" do allow(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end it "should raise an exception if ps fails" do diff --git a/spec/unit/provider/service/solaris_smf_service_spec.rb b/spec/unit/provider/service/solaris_smf_service_spec.rb index 2f790a0ebb..2039408914 100644 --- a/spec/unit/provider/service/solaris_smf_service_spec.rb +++ b/spec/unit/provider/service/solaris_smf_service_spec.rb @@ -85,14 +85,14 @@ describe Chef::Provider::Service::Solaris do it "should not mark service as maintenance" do allow(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@provider.maintenance).to be_false + expect(@provider.maintenance).to be_falsey end it "should mark service as maintenance" do @status = double("Status", :exitstatus => 0, :stdout => 'state maintenance') allow(@provider).to receive(:shell_out!).and_return(@status) @provider.load_current_resource - expect(@provider.maintenance).to be_true + expect(@provider.maintenance).to be_truthy end end @@ -105,15 +105,15 @@ describe Chef::Provider::Service::Solaris do it "should call svcadm enable -s chef" do expect(@provider).not_to receive(:shell_out!).with("/usr/sbin/svcadm clear #{@current_resource.service_name}") expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm enable -s #{@current_resource.service_name}").and_return(@status) - expect(@provider.enable_service).to be_true - expect(@current_resource.enabled).to be_true + expect(@provider.enable_service).to be_truthy + expect(@current_resource.enabled).to be_truthy end it "should call svcadm enable -s chef for start_service" do expect(@provider).not_to receive(:shell_out!).with("/usr/sbin/svcadm clear #{@current_resource.service_name}") expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm enable -s #{@current_resource.service_name}").and_return(@status) - expect(@provider.start_service).to be_true - expect(@current_resource.enabled).to be_true + expect(@provider.start_service).to be_truthy + expect(@current_resource.enabled).to be_truthy end it "should call svcadm clear chef for start_service when state maintenance" do @@ -122,8 +122,8 @@ describe Chef::Provider::Service::Solaris do @provider.load_current_resource expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm clear #{@current_resource.service_name}").and_return(@status) expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm enable -s #{@current_resource.service_name}").and_return(@status) - expect(@provider.enable_service).to be_true - expect(@current_resource.enabled).to be_true + expect(@provider.enable_service).to be_truthy + expect(@current_resource.enabled).to be_truthy end end @@ -135,14 +135,14 @@ describe Chef::Provider::Service::Solaris do it "should call svcadm disable -s chef" do expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm disable -s chef").and_return(@status) - expect(@provider.disable_service).to be_true - expect(@current_resource.enabled).to be_false + expect(@provider.disable_service).to be_truthy + expect(@current_resource.enabled).to be_falsey end it "should call svcadm disable -s chef for stop_service" do expect(@provider).to receive(:shell_out!).with("/usr/sbin/svcadm disable -s chef").and_return(@status) - expect(@provider.stop_service).to be_true - expect(@current_resource.enabled).to be_false + expect(@provider.stop_service).to be_truthy + expect(@current_resource.enabled).to be_falsey end end @@ -170,13 +170,13 @@ describe Chef::Provider::Service::Solaris do it "should be marked not running" do expect(@provider).to receive(:shell_out!).with("/bin/svcs -l chef", {:returns=>[0, 1]}).and_return(@status) @provider.service_status - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end it "should be marked not enabled" do expect(@provider).to receive(:shell_out!).with("/bin/svcs -l chef", {:returns=>[0, 1]}).and_return(@status) @provider.service_status - expect(@current_resource.enabled).to be_false + expect(@current_resource.enabled).to be_falsey end end diff --git a/spec/unit/provider/service/systemd_service_spec.rb b/spec/unit/provider/service/systemd_service_spec.rb index 2fed6bfd11..2bdbdaad05 100644 --- a/spec/unit/provider/service/systemd_service_spec.rb +++ b/spec/unit/provider/service/systemd_service_spec.rb @@ -82,7 +82,7 @@ describe Chef::Provider::Service::Systemd do it "should run the services status command if one has been specified and properly set status check state" do allow(@provider).to receive(:shell_out).with("/bin/chefhasmonkeypants status").and_return(@shell_out_success) @provider.load_current_resource - expect(@provider.instance_variable_get("@status_check_success")).to be_true + expect(@provider.instance_variable_get("@status_check_success")).to be_truthy end it "should set running to false if a status command fails" do @@ -94,7 +94,7 @@ describe Chef::Provider::Service::Systemd do it "should update state to indicate status check failed when a status command fails" do allow(@provider).to receive(:shell_out).and_return(@shell_out_failure) @provider.load_current_resource - expect(@provider.instance_variable_get("@status_check_success")).to be_false + expect(@provider.instance_variable_get("@status_check_success")).to be_falsey end end @@ -228,12 +228,12 @@ describe Chef::Provider::Service::Systemd do it "should return true if '/bin/systemctl is-active service_name' returns 0" do expect(@provider).to receive(:shell_out).with('/bin/systemctl is-active rsyslog.service --quiet').and_return(@shell_out_success) - expect(@provider.is_active?).to be_true + expect(@provider.is_active?).to be_truthy end it "should return false if '/bin/systemctl is-active service_name' returns anything except 0" do expect(@provider).to receive(:shell_out).with('/bin/systemctl is-active rsyslog.service --quiet').and_return(@shell_out_failure) - expect(@provider.is_active?).to be_false + expect(@provider.is_active?).to be_falsey end end @@ -245,12 +245,12 @@ describe Chef::Provider::Service::Systemd do it "should return true if '/bin/systemctl is-enabled service_name' returns 0" do expect(@provider).to receive(:shell_out).with('/bin/systemctl is-enabled rsyslog.service --quiet').and_return(@shell_out_success) - expect(@provider.is_enabled?).to be_true + expect(@provider.is_enabled?).to be_truthy end it "should return false if '/bin/systemctl is-enabled service_name' returns anything except 0" do expect(@provider).to receive(:shell_out).with('/bin/systemctl is-enabled rsyslog.service --quiet').and_return(@shell_out_failure) - expect(@provider.is_enabled?).to be_false + expect(@provider.is_enabled?).to be_falsey end end end diff --git a/spec/unit/provider/service/upstart_service_spec.rb b/spec/unit/provider/service/upstart_service_spec.rb index 69948fbc6a..ca7ce8f930 100644 --- a/spec/unit/provider/service/upstart_service_spec.rb +++ b/spec/unit/provider/service/upstart_service_spec.rb @@ -108,14 +108,14 @@ describe Chef::Provider::Service::Upstart do @stdout = StringIO.new("rsyslog start/running") allow(@provider).to receive(:popen4).and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end it "should set running to false if the status command returns anything except 0" do @stdout = StringIO.new("rsyslog stop/waiting") allow(@provider).to receive(:popen4).and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end end @@ -124,14 +124,14 @@ describe Chef::Provider::Service::Upstart do @stdout = StringIO.new("rsyslog (start) running, process 32225") allow(@provider).to receive(:popen4).and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_true + expect(@current_resource.running).to be_truthy end it "should set running to false if the status command returns anything except 0" do @stdout = StringIO.new("rsyslog (stop) waiting") allow(@provider).to receive(:popen4).and_yield(@pid, @stdin, @stdout, @stderr).and_return(@status) @provider.load_current_resource - expect(@current_resource.running).to be_false + expect(@current_resource.running).to be_falsey end end diff --git a/spec/unit/provider/service/windows_spec.rb b/spec/unit/provider/service/windows_spec.rb index f35f169bc4..e4b0714d22 100644 --- a/spec/unit/provider/service/windows_spec.rb +++ b/spec/unit/provider/service/windows_spec.rb @@ -51,12 +51,12 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do it "should set the current resources status" do @provider.load_current_resource - expect(@provider.current_resource.running).to be_true + expect(@provider.current_resource.running).to be_truthy end it "should set the current resources start type" do @provider.load_current_resource - expect(@provider.current_resource.enabled).to be_true + expect(@provider.current_resource.enabled).to be_truthy end it "does not set the current resources start type if it is neither AUTO START or DISABLED" do @@ -77,20 +77,20 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @new_resource.start_command "sc start chef" expect(@provider).to receive(:shell_out!).with("#{@new_resource.start_command}").and_return("Starting custom service") @provider.start_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should use the built-in command if no start command is specified" do expect(Win32::Service).to receive(:start).with(@new_resource.service_name) @provider.start_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should do nothing if the service does not exist" do allow(Win32::Service).to receive(:exists?).with(@new_resource.service_name).and_return(false) expect(Win32::Service).not_to receive(:start).with(@new_resource.service_name) @provider.start_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should do nothing if the service is running" do @@ -99,7 +99,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:start).with(@new_resource.service_name) @provider.start_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should raise an error if the service is paused" do @@ -108,7 +108,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:start).with(@new_resource.service_name) expect { @provider.start_service }.to raise_error( Chef::Exceptions::Service ) - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should wait and continue if the service is in start_pending" do @@ -119,7 +119,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:start).with(@new_resource.service_name) @provider.start_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should fail if the service is in stop_pending" do @@ -128,7 +128,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:start).with(@new_resource.service_name) expect { @provider.start_service }.to raise_error( Chef::Exceptions::Service ) - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end end @@ -146,20 +146,20 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @new_resource.stop_command "sc stop chef" expect(@provider).to receive(:shell_out!).with("#{@new_resource.stop_command}").and_return("Stopping custom service") @provider.stop_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should use the built-in command if no stop command is specified" do expect(Win32::Service).to receive(:stop).with(@new_resource.service_name) @provider.stop_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should do nothing if the service does not exist" do allow(Win32::Service).to receive(:exists?).with(@new_resource.service_name).and_return(false) expect(Win32::Service).not_to receive(:stop).with(@new_resource.service_name) @provider.stop_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should do nothing if the service is stopped" do @@ -168,7 +168,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:stop).with(@new_resource.service_name) @provider.stop_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should raise an error if the service is paused" do @@ -177,7 +177,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:start).with(@new_resource.service_name) expect { @provider.stop_service }.to raise_error( Chef::Exceptions::Service ) - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should wait and continue if the service is in stop_pending" do @@ -188,7 +188,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:stop).with(@new_resource.service_name) @provider.stop_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should fail if the service is in start_pending" do @@ -197,7 +197,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @provider.load_current_resource expect(Win32::Service).not_to receive(:stop).with(@new_resource.service_name) expect { @provider.stop_service }.to raise_error( Chef::Exceptions::Service ) - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end it "should pass custom timeout to the stop command if provided" do @@ -208,7 +208,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do Timeout.timeout(2) do expect { @provider.stop_service }.to raise_error(Timeout::Error) end - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end end @@ -219,7 +219,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do @new_resource.restart_command "sc restart" expect(@provider).to receive(:shell_out!).with("#{@new_resource.restart_command}") @provider.restart_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should stop then start the service if it is running" do @@ -231,7 +231,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do expect(Win32::Service).to receive(:stop).with(@new_resource.service_name) expect(Win32::Service).to receive(:start).with(@new_resource.service_name) @provider.restart_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should just start the service if it is stopped" do @@ -241,7 +241,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do double("StatusStruct", :current_state => "running")) expect(Win32::Service).to receive(:start).with(@new_resource.service_name) @provider.restart_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should do nothing if the service does not exist" do @@ -249,7 +249,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do expect(Win32::Service).not_to receive(:stop).with(@new_resource.service_name) expect(Win32::Service).not_to receive(:start).with(@new_resource.service_name) @provider.restart_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end end @@ -263,14 +263,14 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do it "should enable service" do expect(Win32::Service).to receive(:configure).with(:service_name => @new_resource.service_name, :start_type => Win32::Service::AUTO_START) @provider.enable_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should do nothing if the service does not exist" do allow(Win32::Service).to receive(:exists?).with(@new_resource.service_name).and_return(false) expect(Win32::Service).not_to receive(:configure) @provider.enable_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end end @@ -315,14 +315,14 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do it "should disable service" do expect(Win32::Service).to receive(:configure) @provider.disable_service - expect(@new_resource.updated_by_last_action?).to be_true + expect(@new_resource.updated_by_last_action?).to be_truthy end it "should do nothing if the service does not exist" do allow(Win32::Service).to receive(:exists?).with(@new_resource.service_name).and_return(false) expect(Win32::Service).not_to receive(:configure) @provider.disable_service - expect(@new_resource.updated_by_last_action?).to be_false + expect(@new_resource.updated_by_last_action?).to be_falsey end end diff --git a/spec/unit/provider/service_spec.rb b/spec/unit/provider/service_spec.rb index e60b08e7f0..17bade55b6 100644 --- a/spec/unit/provider/service_spec.rb +++ b/spec/unit/provider/service_spec.rb @@ -69,7 +69,7 @@ describe Chef::Provider::Service do describe "action_start" do it "should start the service if it isn't running and set the resource as updated" do @current_resource.running(false) - expect(@provider).to receive(:start_service).with.and_return(true) + expect(@provider).to receive(:start_service).with(no_args).and_return(true) @provider.run_action(:start) expect(@provider.new_resource).to be_updated end diff --git a/spec/unit/provider/user/dscl_spec.rb b/spec/unit/provider/user/dscl_spec.rb index c8dbef770e..24691cce33 100644 --- a/spec/unit/provider/user/dscl_spec.rb +++ b/spec/unit/provider/user/dscl_spec.rb @@ -171,7 +171,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" describe "uid_used?" do it "should return false if not given any valid uid number" do - expect(provider.uid_used?(nil)).to be_false + expect(provider.uid_used?(nil)).to be_falsey end describe "when called with a user id" do @@ -180,11 +180,11 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" end it "should return true for a used uid number" do - expect(provider.uid_used?(500)).to be_true + expect(provider.uid_used?(500)).to be_truthy end it "should return false for an unused uid number" do - expect(provider.uid_used?(501)).to be_false + expect(provider.uid_used?(501)).to be_falsey end end end @@ -400,7 +400,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" it "should set @user_exists" do provider.load_current_resource - expect(provider.instance_variable_get(:@user_exists)).to be_false + expect(provider.instance_variable_get(:@user_exists)).to be_falsey end it "should set username" do @@ -434,7 +434,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" it "diverged_password? should report false" do provider.load_current_resource - expect(provider.diverged_password?).to be_false + expect(provider.diverged_password?).to be_falsey end end @@ -443,7 +443,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" it "diverged_password? should report true" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end @@ -453,7 +453,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" it "diverged_password? should report false" do provider.load_current_resource - expect(provider.diverged_password?).to be_false + expect(provider.diverged_password?).to be_falsey end end @@ -462,7 +462,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" it "diverged_password? should report true" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end @@ -472,7 +472,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30" it "diverged_password? should report false" do provider.load_current_resource - expect(provider.diverged_password?).to be_false + expect(provider.diverged_password?).to be_falsey end end end @@ -525,7 +525,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") describe "when a plain text password is set" do it "reports password needs to be updated" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end @@ -536,7 +536,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") it "reports password needs to be updated" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end end @@ -565,7 +565,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") it "diverged_password? should report false" do provider.load_current_resource - expect(provider.diverged_password?).to be_false + expect(provider.diverged_password?).to be_falsey end end @@ -574,7 +574,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") it "diverged_password? should report true" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end @@ -585,7 +585,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") it "diverged_password? should report true" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end @@ -596,7 +596,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") it "diverged_password? should report true" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end @@ -607,7 +607,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") it "diverged_password? should report true" do provider.load_current_resource - expect(provider.diverged_password?).to be_true + expect(provider.diverged_password?).to be_truthy end end end @@ -616,23 +616,23 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") describe "salted_sha512_pbkdf2?" do it "should return true when the string is a salted_sha512_pbkdf2 hash" do - expect(provider.salted_sha512_pbkdf2?(salted_sha512_pbkdf2_password)).to be_true + expect(provider.salted_sha512_pbkdf2?(salted_sha512_pbkdf2_password)).to be_truthy end it "should return false otherwise" do - expect(provider.salted_sha512_pbkdf2?(salted_sha512_password)).to be_false - expect(provider.salted_sha512_pbkdf2?("any other string")).to be_false + expect(provider.salted_sha512_pbkdf2?(salted_sha512_password)).to be_falsey + expect(provider.salted_sha512_pbkdf2?("any other string")).to be_falsey end end describe "salted_sha512?" do it "should return true when the string is a salted_sha512_pbkdf2 hash" do - expect(provider.salted_sha512_pbkdf2?(salted_sha512_pbkdf2_password)).to be_true + expect(provider.salted_sha512_pbkdf2?(salted_sha512_pbkdf2_password)).to be_truthy end it "should return false otherwise" do - expect(provider.salted_sha512?(salted_sha512_pbkdf2_password)).to be_false - expect(provider.salted_sha512?("any other string")).to be_false + expect(provider.salted_sha512?(salted_sha512_pbkdf2_password)).to be_falsey + expect(provider.salted_sha512?("any other string")).to be_falsey end end @@ -649,7 +649,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") shadow_info = provider.prepare_password_shadow_info expect(shadow_info).to have_key("SALTED-SHA512") info = shadow_info["SALTED-SHA512"].string.unpack('H*').first - expect(provider.salted_sha512?(info)).to be_true + expect(provider.salted_sha512?(info)).to be_truthy end end @@ -660,7 +660,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") shadow_info = provider.prepare_password_shadow_info expect(shadow_info).to have_key("SALTED-SHA512") info = shadow_info["SALTED-SHA512"].string.unpack('H*').first - expect(provider.salted_sha512?(info)).to be_true + expect(provider.salted_sha512?(info)).to be_truthy expect(info).to eq(vagrant_sha_512) end end @@ -682,7 +682,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") expect(shadow_info["SALTED-SHA512-PBKDF2"]).to have_key("salt") expect(shadow_info["SALTED-SHA512-PBKDF2"]).to have_key("iterations") info = shadow_info["SALTED-SHA512-PBKDF2"]["entropy"].string.unpack('H*').first - expect(provider.salted_sha512_pbkdf2?(info)).to be_true + expect(provider.salted_sha512_pbkdf2?(info)).to be_truthy end end @@ -698,7 +698,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30") expect(shadow_info["SALTED-SHA512-PBKDF2"]).to have_key("salt") expect(shadow_info["SALTED-SHA512-PBKDF2"]).to have_key("iterations") info = shadow_info["SALTED-SHA512-PBKDF2"]["entropy"].string.unpack('H*').first - expect(provider.salted_sha512_pbkdf2?(info)).to be_true + expect(provider.salted_sha512_pbkdf2?(info)).to be_truthy expect(info).to eq(vagrant_sha_512_pbkdf2) end end diff --git a/spec/unit/provider_spec.rb b/spec/unit/provider_spec.rb index 9b89fc1888..5a21b094d0 100644 --- a/spec/unit/provider_spec.rb +++ b/spec/unit/provider_spec.rb @@ -74,23 +74,23 @@ describe Chef::Provider do end it "should store the resource passed to new as new_resource" do - @provider.new_resource.should eql(@resource) + expect(@provider.new_resource).to eql(@resource) end it "should store the node passed to new as node" do - @provider.node.should eql(@node) + expect(@provider.node).to eql(@node) end it "should have nil for current_resource by default" do - @provider.current_resource.should eql(nil) + expect(@provider.current_resource).to eql(nil) end it "should not support whyrun by default" do - @provider.send(:whyrun_supported?).should eql(false) + expect(@provider.send(:whyrun_supported?)).to eql(false) end it "should return true for action_nothing" do - @provider.action_nothing.should eql(true) + expect(@provider.action_nothing).to eql(true) end it "evals embedded recipes with a pristine resource collection" do @@ -98,27 +98,27 @@ describe Chef::Provider do temporary_collection = nil snitch = Proc.new {temporary_collection = @run_context.resource_collection} @provider.send(:recipe_eval, &snitch) - temporary_collection.should be_an_instance_of(Chef::ResourceCollection) - @provider.run_context.instance_variable_get(:@resource_collection).should == "doesn't matter what this is" + expect(temporary_collection).to be_an_instance_of(Chef::ResourceCollection) + expect(@provider.run_context.instance_variable_get(:@resource_collection)).to eq("doesn't matter what this is") end it "does not re-load recipes when creating the temporary run context" do # we actually want to test that RunContext#load is never called, but we # can't stub all instances of an object with rspec's mocks. :/ - Chef::RunContext.stub(:new).and_raise("not supposed to happen") + allow(Chef::RunContext).to receive(:new).and_raise("not supposed to happen") snitch = Proc.new {temporary_collection = @run_context.resource_collection} @provider.send(:recipe_eval, &snitch) end context "when no converge actions are queued" do before do - @provider.stub(:whyrun_supported?).and_return(true) - @provider.stub(:load_current_resource) + allow(@provider).to receive(:whyrun_supported?).and_return(true) + allow(@provider).to receive(:load_current_resource) end it "does not mark the new resource as updated" do - @resource.should_not be_updated - @resource.should_not be_updated_by_last_action + expect(@resource).not_to be_updated + expect(@resource).not_to be_updated_by_last_action end end @@ -129,23 +129,23 @@ describe Chef::Provider do end it "should tell us that it does support whyrun" do - @provider.should be_whyrun_supported + expect(@provider).to be_whyrun_supported end it "queues up converge actions" do @provider.action_foo - @provider.send(:converge_actions).should have(1).actions + expect(@provider.send(:converge_actions).actions.size).to eq(1) end it "executes pending converge actions to converge the system" do @provider.run_action(:foo) - @provider.instance_variable_get(:@system_state_altered).should be_true + expect(@provider.instance_variable_get(:@system_state_altered)).to be_truthy end it "marks the resource as updated" do @provider.run_action(:foo) - @resource.should be_updated - @resource.should be_updated_by_last_action + expect(@resource).to be_updated + expect(@resource).to be_updated_by_last_action end end @@ -160,20 +160,20 @@ describe Chef::Provider do end it "should tell us that it doesn't support whyrun" do - @provider.should_not be_whyrun_supported + expect(@provider).not_to be_whyrun_supported end it "should automatically generate a converge_by block on the provider's behalf" do @provider.run_action(:foo) - @provider.send(:converge_actions).should have(0).actions - @provider.system_state_altered.should be_false + expect(@provider.send(:converge_actions).actions.size).to eq(0) + expect(@provider.system_state_altered).to be_falsey end it "should automatically execute the generated converge_by block" do @provider.run_action(:foo) - @provider.system_state_altered.should be_false - @resource.should_not be_updated - @resource.should_not be_updated_by_last_action + expect(@provider.system_state_altered).to be_falsey + expect(@resource).not_to be_updated + expect(@resource).not_to be_updated_by_last_action end end end diff --git a/spec/unit/recipe_spec.rb b/spec/unit/recipe_spec.rb index 0e660dc0cc..1b7506d965 100644 --- a/spec/unit/recipe_spec.rb +++ b/spec/unit/recipe_spec.rb @@ -52,50 +52,50 @@ describe Chef::Recipe do describe "method_missing" do describe "resources" do it "should load a two word (zen_master) resource" do - lambda do + expect do recipe.zen_master "monkey" do peace true end - end.should_not raise_error + end.not_to raise_error end it "should load a one word (cat) resource" do - lambda do + expect do recipe.cat "loulou" do pretty_kitty true end - end.should_not raise_error + end.not_to raise_error end it "should load a four word (one_two_three_four) resource" do - lambda do + expect do recipe.one_two_three_four "numbers" do i_can_count true end - end.should_not raise_error + end.not_to raise_error end it "should throw an error if you access a resource that we can't find" do - lambda { recipe.not_home("not_home_resource") }.should raise_error(NameError) + expect { recipe.not_home("not_home_resource") }.to raise_error(NameError) end it "should require a name argument" do - lambda { + expect { recipe.cat - }.should raise_error(ArgumentError, "You must supply a name when declaring a cat resource") + }.to raise_error(ArgumentError, "You must supply a name when declaring a cat resource") end it "should allow regular errors (not NameErrors) to pass unchanged" do - lambda { + expect { recipe.cat("felix") { raise ArgumentError, "You Suck" } - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should add our zen_master to the collection" do recipe.zen_master "monkey" do peace true end - run_context.resource_collection.lookup("zen_master[monkey]").name.should eql("monkey") + expect(run_context.resource_collection.lookup("zen_master[monkey]").name).to eql("monkey") end it "should add our zen masters to the collection in the order they appear" do @@ -105,15 +105,15 @@ describe Chef::Recipe do end end - run_context.resource_collection.map{|r| r.name}.should eql(["monkey", "dog", "cat"]) + expect(run_context.resource_collection.map{|r| r.name}).to eql(["monkey", "dog", "cat"]) end it "should return the new resource after creating it" do res = recipe.zen_master "makoto" do peace true end - res.resource_name.should eql(:zen_master) - res.name.should eql("makoto") + expect(res.resource_name).to eql(:zen_master) + expect(res.name).to eql("makoto") end describe "should locate platform mapped resources" do @@ -124,7 +124,7 @@ describe Chef::Recipe do node.automatic[:platform] = "television" node.automatic[:platform_version] = "123" res = recipe.laughter "timmy" - res.name.should eql("timmy") + expect(res.name).to eql("timmy") res.kind_of?(ShaunTheSheep) end @@ -132,7 +132,7 @@ describe Chef::Recipe do YourMom = Class.new(Chef::Resource) YourMom.provides :love_and_caring res = recipe.love_and_caring "mommy" - res.name.should eql("mommy") + expect(res.name).to eql("mommy") res.kind_of?(YourMom) end @@ -147,13 +147,13 @@ describe Chef::Recipe do end it "applies attributes from the block to the resource" do - zm_resource.something.should == "bvb" + expect(zm_resource.something).to eq("bvb") end it "sets contextual attributes on the resource" do - zm_resource.recipe_name.should == "test" - zm_resource.cookbook_name.should == "hjk" - zm_resource.source_line.should include(__FILE__) + expect(zm_resource.recipe_name).to eq("test") + expect(zm_resource.cookbook_name).to eq("hjk") + expect(zm_resource.source_line).to include(__FILE__) end it "does not add the resource to the resource collection" do @@ -171,18 +171,18 @@ describe Chef::Recipe do end it "applies attributes from the block to the resource" do - zm_resource.something.should == "bvb" + expect(zm_resource.something).to eq("bvb") end it "sets contextual attributes on the resource" do - zm_resource.recipe_name.should == "test" - zm_resource.cookbook_name.should == "hjk" - zm_resource.source_line.should include(__FILE__) + expect(zm_resource.recipe_name).to eq("test") + expect(zm_resource.cookbook_name).to eq("hjk") + expect(zm_resource.source_line).to include(__FILE__) end it "adds the resource to the resource collection" do zm_resource # force let binding evaluation - run_context.resource_collection.resources(:zen_master => "klopp").should == zm_resource + expect(run_context.resource_collection.resources(:zen_master => "klopp")).to eq(zm_resource) end end @@ -201,7 +201,7 @@ describe Chef::Recipe do it "defines the resource using the declaration name with short name" do resource_follower - run_context.resource_collection.lookup("follower[srst]").should_not be_nil + expect(run_context.resource_collection.lookup("follower[srst]")).not_to be_nil end end @@ -215,25 +215,25 @@ describe Chef::Recipe do it "defines the resource using the declaration name with long name" do resource_zn_follower - run_context.resource_collection.lookup("zen_follower[srst]").should_not be_nil + expect(run_context.resource_collection.lookup("zen_follower[srst]")).not_to be_nil end end describe "when attempting to create a resource of an invalid type" do it "gives a sane error message when using method_missing" do - lambda do + expect do recipe.no_such_resource("foo") - end.should raise_error(NoMethodError, %q[No resource or method named `no_such_resource' for `Chef::Recipe "test"']) + end.to raise_error(NoMethodError, %q[No resource or method named `no_such_resource' for `Chef::Recipe "test"']) end it "gives a sane error message when using method_missing 'bare'" do - lambda do + expect do recipe.instance_eval do # Giving an argument will change this from NameError to NoMethodError no_such_resource end - end.should raise_error(NameError, %q[No resource, method, or local variable named `no_such_resource' for `Chef::Recipe "test"']) + end.to raise_error(NameError, %q[No resource, method, or local variable named `no_such_resource' for `Chef::Recipe "test"']) end it "gives a sane error message when using build_resource" do @@ -249,11 +249,11 @@ describe Chef::Recipe do describe "when creating a resource that contains an error in the attributes block" do it "does not obfuscate the error source" do - lambda do + expect do recipe.zen_master("klopp") do this_method_doesnt_exist end - end.should raise_error(NoMethodError, "undefined method `this_method_doesnt_exist' for Chef::Resource::ZenMaster") + end.to raise_error(NoMethodError, "undefined method `this_method_doesnt_exist' for Chef::Resource::ZenMaster") end @@ -280,28 +280,28 @@ describe Chef::Recipe do end it "copies attributes from the first resource" do - duplicated_resource.something.should == "bvb09" + expect(duplicated_resource.something).to eq("bvb09") end it "does not copy the action from the first resource" do - original_resource.action.should == [:score] - duplicated_resource.action.should == :nothing + expect(original_resource.action).to eq([:score]) + expect(duplicated_resource.action).to eq(:nothing) end it "does not copy the source location of the first resource" do # sanity check source location: - original_resource.source_line.should include(__FILE__) - duplicated_resource.source_line.should include(__FILE__) + expect(original_resource.source_line).to include(__FILE__) + expect(duplicated_resource.source_line).to include(__FILE__) # actual test: - original_resource.source_line.should_not == duplicated_resource.source_line + expect(original_resource.source_line).not_to eq(duplicated_resource.source_line) end it "sets the cookbook name on the cloned resource to that resource's cookbook" do - duplicated_resource.cookbook_name.should == "second_cb" + expect(duplicated_resource.cookbook_name).to eq("second_cb") end it "sets the recipe name on the cloned resource to that resoure's recipe" do - duplicated_resource.recipe_name.should == "second_recipe" + expect(duplicated_resource.recipe_name).to eq("second_recipe") end end @@ -319,8 +319,8 @@ describe Chef::Recipe do recipe.crow "mine" do peace true end - run_context.resource_collection.resources(:zen_master => "lao tzu").name.should eql("lao tzu") - run_context.resource_collection.resources(:zen_master => "lao tzu").something.should eql(true) + expect(run_context.resource_collection.resources(:zen_master => "lao tzu").name).to eql("lao tzu") + expect(run_context.resource_collection.resources(:zen_master => "lao tzu").something).to eql(true) end it "should set the node on defined resources" do @@ -336,7 +336,7 @@ describe Chef::Recipe do recipe.crow "mine" do something node[:foo] end - recipe.resources(:zen_master => "lao tzu").something.should eql(false) + expect(recipe.resources(:zen_master => "lao tzu").something).to eql(false) end it "should return the last statement in the definition as the retval" do @@ -345,9 +345,10 @@ describe Chef::Recipe do "the return val" end run_context.definitions[:crow] = crow_define - recipe.crow "mine" do + crow_block = recipe.crow "mine" do peace true - end.should eql("the return val") + end + expect(crow_block).to eql("the return val") end end @@ -360,8 +361,8 @@ describe Chef::Recipe do peace = true end CODE - lambda { recipe.instance_eval(code) }.should_not raise_error - recipe.resources(:zen_master => "gnome").name.should eql("gnome") + expect { recipe.instance_eval(code) }.not_to raise_error + expect(recipe.resources(:zen_master => "gnome").name).to eql("gnome") end end @@ -370,7 +371,7 @@ describe Chef::Recipe do code = <<-CODE exec 'do_not_try_to_exec' CODE - lambda { recipe.instance_eval(code) }.should raise_error(Chef::Exceptions::ResourceNotFound) + expect { recipe.instance_eval(code) }.to raise_error(Chef::Exceptions::ResourceNotFound) end end @@ -378,50 +379,50 @@ describe Chef::Recipe do it "should load a resource from a ruby file" do recipe.from_file(File.join(CHEF_SPEC_DATA, "recipes", "test.rb")) res = recipe.resources(:file => "/etc/nsswitch.conf") - res.name.should eql("/etc/nsswitch.conf") - res.action.should eql([:create]) - res.owner.should eql("root") - res.group.should eql("root") - res.mode.should eql(0644) + expect(res.name).to eql("/etc/nsswitch.conf") + expect(res.action).to eql([:create]) + expect(res.owner).to eql("root") + expect(res.group).to eql("root") + expect(res.mode).to eql(0644) end it "should raise an exception if the file cannot be found or read" do - lambda { recipe.from_file("/tmp/monkeydiving") }.should raise_error(IOError) + expect { recipe.from_file("/tmp/monkeydiving") }.to raise_error(IOError) end end describe "include_recipe" do it "should evaluate another recipe with include_recipe" do - node.should_receive(:loaded_recipe).with(:openldap, "gigantor") - run_context.stub(:unreachable_cookbook?).with(:openldap).and_return(false) + expect(node).to receive(:loaded_recipe).with(:openldap, "gigantor") + allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false) run_context.include_recipe "openldap::gigantor" res = run_context.resource_collection.resources(:cat => "blanket") - res.name.should eql("blanket") - res.pretty_kitty.should eql(false) + expect(res.name).to eql("blanket") + expect(res.pretty_kitty).to eql(false) end it "should load the default recipe for a cookbook if include_recipe is called without a ::" do - node.should_receive(:loaded_recipe).with(:openldap, "default") - run_context.stub(:unreachable_cookbook?).with(:openldap).and_return(false) + expect(node).to receive(:loaded_recipe).with(:openldap, "default") + allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false) run_context.include_recipe "openldap" res = run_context.resource_collection.resources(:cat => "blanket") - res.name.should eql("blanket") - res.pretty_kitty.should eql(true) + expect(res.name).to eql("blanket") + expect(res.pretty_kitty).to eql(true) end it "should store that it has seen a recipe in the run_context" do - node.should_receive(:loaded_recipe).with(:openldap, "default") - run_context.stub(:unreachable_cookbook?).with(:openldap).and_return(false) + expect(node).to receive(:loaded_recipe).with(:openldap, "default") + allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false) run_context.include_recipe "openldap" - run_context.loaded_recipe?("openldap").should be_true + expect(run_context.loaded_recipe?("openldap")).to be_truthy end it "should not include the same recipe twice" do - node.should_receive(:loaded_recipe).with(:openldap, "default").exactly(:once) - run_context.stub(:unreachable_cookbook?).with(:openldap).and_return(false) - cookbook_collection[:openldap].should_receive(:load_recipe).with("default", run_context) + expect(node).to receive(:loaded_recipe).with(:openldap, "default").exactly(:once) + allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false) + expect(cookbook_collection[:openldap]).to receive(:load_recipe).with("default", run_context) recipe.include_recipe "openldap" - cookbook_collection[:openldap].should_not_receive(:load_recipe).with("default", run_context) + expect(cookbook_collection[:openldap]).not_to receive(:load_recipe).with("default", run_context) recipe.include_recipe "openldap" end end @@ -431,55 +432,55 @@ describe Chef::Recipe do let(:node) { Chef::Node.new } it "should return false for any tags" do - recipe.tagged?("foo").should be(false) + expect(recipe.tagged?("foo")).to be(false) end end it "should set tags via tag" do recipe.tag "foo" - node[:tags].should include("foo") + expect(node[:tags]).to include("foo") end it "should set multiple tags via tag" do recipe.tag "foo", "bar" - node[:tags].should include("foo") - node[:tags].should include("bar") + expect(node[:tags]).to include("foo") + expect(node[:tags]).to include("bar") end it "should not set the same tag twice via tag" do recipe.tag "foo" recipe.tag "foo" - node[:tags].should eql([ "foo" ]) + expect(node[:tags]).to eql([ "foo" ]) end it "should return the current list of tags from tag with no arguments" do recipe.tag "foo" - recipe.tag.should eql([ "foo" ]) + expect(recipe.tag).to eql([ "foo" ]) end it "should return true from tagged? if node is tagged" do recipe.tag "foo" - recipe.tagged?("foo").should be(true) + expect(recipe.tagged?("foo")).to be(true) end it "should return false from tagged? if node is not tagged" do - recipe.tagged?("foo").should be(false) + expect(recipe.tagged?("foo")).to be(false) end it "should return false from tagged? if node is not tagged" do - recipe.tagged?("foo").should be(false) + expect(recipe.tagged?("foo")).to be(false) end it "should remove a tag from the tag list via untag" do recipe.tag "foo" recipe.untag "foo" - node[:tags].should eql([]) + expect(node[:tags]).to eql([]) end it "should remove multiple tags from the tag list via untag" do recipe.tag "foo", "bar" recipe.untag "bar", "foo" - node[:tags].should eql([]) + expect(node[:tags]).to eql([]) end end end diff --git a/spec/unit/registry_helper_spec.rb b/spec/unit/registry_helper_spec.rb index 444a82dc7c..036a0834db 100644 --- a/spec/unit/registry_helper_spec.rb +++ b/spec/unit/registry_helper_spec.rb @@ -29,7 +29,7 @@ describe Chef::Provider::RegistryKey do let(:missing_key_path) {'HKCU\Software'} before(:each) do - Chef::Win32::Registry.any_instance.stub(:machine_architecture).and_return(:x86_64) + allow_any_instance_of(Chef::Win32::Registry).to receive(:machine_architecture).and_return(:x86_64) @registry = Chef::Win32::Registry.new() #Making the values for registry constants available on unix @@ -49,328 +49,328 @@ describe Chef::Provider::RegistryKey do describe "get_values" do it "gets all values for a key if the key exists" do - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:map) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:map) @registry.get_values(key_path) end it "throws an exception if key does not exist" do - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - lambda{@registry.get_values(key_path)}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) + expect{@registry.get_values(key_path)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end describe "set_value" do it "does nothing if key and hive and value exist" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(true) - @registry.should_receive(:data_exists?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:data_exists?).with(key_path, value1).and_return(true) @registry.set_value(key_path, value1) end it "updates value if key and hive and value exist, but data is different" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(true) - @registry.should_receive(:data_exists?).with(key_path, value1).and_return(false) - @hive_mock.should_receive(:open).with(key, Win32::Registry::KEY_SET_VALUE | ::Win32::Registry::KEY_QUERY_VALUE | @registry.registry_system_architecture).and_yield(@reg_mock) - @registry.should_receive(:get_type_from_name).with(:string).and_return(1) - @reg_mock.should_receive(:write).with("one", 1, "1") + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:data_exists?).with(key_path, value1).and_return(false) + expect(@hive_mock).to receive(:open).with(key, Win32::Registry::KEY_SET_VALUE | ::Win32::Registry::KEY_QUERY_VALUE | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@registry).to receive(:get_type_from_name).with(:string).and_return(1) + expect(@reg_mock).to receive(:write).with("one", 1, "1") @registry.set_value(key_path, value1) end it "creates value if the key exists and the value does not exist" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(false) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_SET_VALUE | ::Win32::Registry::KEY_QUERY_VALUE | @registry.registry_system_architecture).and_yield(@reg_mock) - @registry.should_receive(:get_type_from_name).with(:string).and_return(1) - @reg_mock.should_receive(:write).with("one", 1, "1") + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(false) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_SET_VALUE | ::Win32::Registry::KEY_QUERY_VALUE | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@registry).to receive(:get_type_from_name).with(:string).and_return(1) + expect(@reg_mock).to receive(:write).with("one", 1, "1") @registry.set_value(key_path, value1) end it "should raise an exception if the key does not exist" do - @registry.should_receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - lambda {@registry.set_value(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect(@registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.set_value(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end describe "delete_value" do it "deletes value if value exists" do - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_SET_VALUE | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:delete_value).with("one").and_return(true) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_SET_VALUE | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:delete_value).with("one").and_return(true) @registry.delete_value(key_path, value1) end it "raises an exception if the key does not exist" do - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) @registry.delete_value(key_path, value1) end it "does nothing if the value does not exist" do - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(false) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(false) @registry.delete_value(key_path, value1) end end describe "create_key" do it "creates key if intermediate keys are missing and recursive is set to true" do - @registry.should_receive(:keys_missing?).with(key_path).and_return(true) - @registry.should_receive(:create_missing).with(key_path) - @registry.should_receive(:key_exists?).with(key_path).and_return(false) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:create).with(key, ::Win32::Registry::KEY_WRITE | @registry.registry_system_architecture) + expect(@registry).to receive(:keys_missing?).with(key_path).and_return(true) + expect(@registry).to receive(:create_missing).with(key_path) + expect(@registry).to receive(:key_exists?).with(key_path).and_return(false) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:create).with(key, ::Win32::Registry::KEY_WRITE | @registry.registry_system_architecture) @registry.create_key(key_path, true) end it "raises an exception if intermediate keys are missing and recursive is set to false" do - @registry.should_receive(:keys_missing?).with(key_path).and_return(true) - lambda{@registry.create_key(key_path, false)}.should raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect(@registry).to receive(:keys_missing?).with(key_path).and_return(true) + expect{@registry.create_key(key_path, false)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "does nothing if the key exists" do - @registry.should_receive(:keys_missing?).with(key_path).and_return(true) - @registry.should_receive(:create_missing).with(key_path) - @registry.should_receive(:key_exists?).with(key_path).and_return(true) + expect(@registry).to receive(:keys_missing?).with(key_path).and_return(true) + expect(@registry).to receive(:create_missing).with(key_path) + expect(@registry).to receive(:key_exists?).with(key_path).and_return(true) @registry.create_key(key_path, true) end it "create key if intermediate keys not missing and recursive is set to false" do - @registry.should_receive(:keys_missing?).with(key_path).and_return(false) - @registry.should_receive(:key_exists?).with(key_path).and_return(false) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:create).with(key, ::Win32::Registry::KEY_WRITE | @registry.registry_system_architecture) + expect(@registry).to receive(:keys_missing?).with(key_path).and_return(false) + expect(@registry).to receive(:key_exists?).with(key_path).and_return(false) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:create).with(key, ::Win32::Registry::KEY_WRITE | @registry.registry_system_architecture) @registry.create_key(key_path, false) end it "create key if intermediate keys not missing and recursive is set to true" do - @registry.should_receive(:keys_missing?).with(key_path).and_return(false) - @registry.should_receive(:key_exists?).with(key_path).and_return(false) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:create).with(key, ::Win32::Registry::KEY_WRITE | @registry.registry_system_architecture) + expect(@registry).to receive(:keys_missing?).with(key_path).and_return(false) + expect(@registry).to receive(:key_exists?).with(key_path).and_return(false) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:create).with(key, ::Win32::Registry::KEY_WRITE | @registry.registry_system_architecture) @registry.create_key(key_path, true) end end describe "delete_key", :windows_only do it "deletes key if it has subkeys and recursive is set to true" do - @registry.should_receive(:key_exists?).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:has_subkeys?).with(key_path).and_return(true) - @registry.should_receive(:get_subkeys).with(key_path).and_return([sub_key]) - @registry.should_receive(:key_exists?).with(key_path+"\\"+sub_key).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path+"\\"+sub_key).and_return([@hive_mock, key+"\\"+sub_key]) - @registry.should_receive(:has_subkeys?).with(key_path+"\\"+sub_key).and_return(false) - @registry.should_receive(:delete_key_ex).twice + expect(@registry).to receive(:key_exists?).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:has_subkeys?).with(key_path).and_return(true) + expect(@registry).to receive(:get_subkeys).with(key_path).and_return([sub_key]) + expect(@registry).to receive(:key_exists?).with(key_path+"\\"+sub_key).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path+"\\"+sub_key).and_return([@hive_mock, key+"\\"+sub_key]) + expect(@registry).to receive(:has_subkeys?).with(key_path+"\\"+sub_key).and_return(false) + expect(@registry).to receive(:delete_key_ex).twice @registry.delete_key(key_path, true) end it "raises an exception if it has subkeys but recursive is set to false" do - @registry.should_receive(:key_exists?).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:has_subkeys?).with(key_path).and_return(true) - lambda{@registry.delete_key(key_path, false)}.should raise_error(Chef::Exceptions::Win32RegNoRecursive) + expect(@registry).to receive(:key_exists?).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:has_subkeys?).with(key_path).and_return(true) + expect{@registry.delete_key(key_path, false)}.to raise_error(Chef::Exceptions::Win32RegNoRecursive) end it "deletes key if the key exists and has no subkeys" do - @registry.should_receive(:key_exists?).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:has_subkeys?).with(key_path).and_return(false) - @registry.should_receive(:delete_key_ex) + expect(@registry).to receive(:key_exists?).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:has_subkeys?).with(key_path).and_return(false) + expect(@registry).to receive(:delete_key_ex) @registry.delete_key(key_path, true) end end describe "key_exists?" do it "returns true if key_exists" do - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @registry.key_exists?(key_path).should == true + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@registry.key_exists?(key_path)).to eq(true) end it "returns false if key does not exist" do - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_raise(::Win32::Registry::Error) - @registry.key_exists?(key_path).should == false + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_raise(::Win32::Registry::Error) + expect(@registry.key_exists?(key_path)).to eq(false) end end describe "key_exists!" do it "throws an exception if the key_parent does not exist" do - @registry.should_receive(:key_exists?).with(key_path).and_return(false) - lambda{@registry.key_exists!(key_path)}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect(@registry).to receive(:key_exists?).with(key_path).and_return(false) + expect{@registry.key_exists!(key_path)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end describe "hive_exists?" do it "returns true if the hive exists" do - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) @registry.hive_exists?(key_path) == true end it "returns false if the hive does not exist" do - @registry.should_receive(:get_hive_and_key).with(key_path).and_raise(Chef::Exceptions::Win32RegHiveMissing) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_raise(Chef::Exceptions::Win32RegHiveMissing) @registry.hive_exists?(key_path) == false end end describe "has_subkeys?" do it "returns true if the key has subkeys" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:each_key).and_yield(key) + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:each_key).and_yield(key) @registry.has_subkeys?(key_path) == true end it "returns false if the key does not have subkeys" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:each_key).and_return(no_args()) - @registry.has_subkeys?(key_path).should == false + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:each_key).and_return(no_args()) + expect(@registry.has_subkeys?(key_path)).to eq(false) end it "throws an exception if the key does not exist" do - @registry.should_receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - lambda {@registry.set_value(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect(@registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.set_value(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end end describe "get_subkeys" do it "returns the subkeys if they exist" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:each_key).and_yield(sub_key) + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:each_key).and_yield(sub_key) @registry.get_subkeys(key_path) end end describe "value_exists?" do it "throws an exception if the key does not exist" do - @registry.should_receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - lambda {@registry.value_exists?(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect(@registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.value_exists?(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the value exists" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:any?).and_yield("one") + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:any?).and_yield("one") @registry.value_exists?(key_path, value1) == true end it "returns false if the value does not exist" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:any?).and_yield(no_args()) + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:any?).and_yield(no_args()) @registry.value_exists?(key_path, value1) == false end end describe "data_exists?" do it "throws an exception if the key does not exist" do - @registry.should_receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) - lambda {@registry.data_exists?(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegKeyMissing) + expect(@registry).to receive(:key_exists!).with(key_path).and_raise(Chef::Exceptions::Win32RegKeyMissing) + expect {@registry.data_exists?(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegKeyMissing) end it "returns true if the data exists" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @registry.should_receive(:get_type_from_name).with(:string).and_return(1) - @reg_mock.should_receive(:each).with(no_args()).and_yield("one", 1, "1") - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @registry.data_exists?(key_path, value1).should == true + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@registry).to receive(:get_type_from_name).with(:string).and_return(1) + expect(@reg_mock).to receive(:each).with(no_args()).and_yield("one", 1, "1") + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@registry.data_exists?(key_path, value1)).to eq(true) end it "returns false if the data does not exist" do - @registry.should_receive(:key_exists!).with(key_path).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @registry.should_receive(:get_type_from_name).with(:string).and_return(1) - @reg_mock.should_receive(:each).with(no_args()).and_yield("one", 1, "2") - @registry.data_exists?(key_path, value1).should == false + expect(@registry).to receive(:key_exists!).with(key_path).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@registry).to receive(:get_type_from_name).with(:string).and_return(1) + expect(@reg_mock).to receive(:each).with(no_args()).and_yield("one", 1, "2") + expect(@registry.data_exists?(key_path, value1)).to eq(false) end end describe "value_exists!" do it "does nothing if the value exists" do - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(true) @registry.value_exists!(key_path, value1) end it "throws an exception if the value does not exist" do - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(false) - lambda{@registry.value_exists!(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegValueMissing) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(false) + expect{@registry.value_exists!(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegValueMissing) end end describe "data_exists!" do it "does nothing if the data exists" do - @registry.should_receive(:data_exists?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:data_exists?).with(key_path, value1).and_return(true) @registry.data_exists!(key_path, value1) end it "throws an exception if the data does not exist" do - @registry.should_receive(:data_exists?).with(key_path, value1).and_return(false) - lambda{@registry.data_exists!(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegDataMissing) + expect(@registry).to receive(:data_exists?).with(key_path, value1).and_return(false) + expect{@registry.data_exists!(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegDataMissing) end end describe "type_matches?" do it "returns true if type matches" do - @registry.should_receive(:value_exists!).with(key_path, value1).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @registry.should_receive(:get_type_from_name).with(:string).and_return(1) - @reg_mock.should_receive(:each).and_yield("one", 1) - @registry.type_matches?(key_path, value1).should == true + expect(@registry).to receive(:value_exists!).with(key_path, value1).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@registry).to receive(:get_type_from_name).with(:string).and_return(1) + expect(@reg_mock).to receive(:each).and_yield("one", 1) + expect(@registry.type_matches?(key_path, value1)).to eq(true) end it "returns false if type does not match" do - @registry.should_receive(:value_exists!).with(key_path, value1).and_return(true) - @registry.should_receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) - @hive_mock.should_receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) - @reg_mock.should_receive(:each).and_yield("two", 2) - @registry.type_matches?(key_path, value1).should == false + expect(@registry).to receive(:value_exists!).with(key_path, value1).and_return(true) + expect(@registry).to receive(:get_hive_and_key).with(key_path).and_return([@hive_mock, key]) + expect(@hive_mock).to receive(:open).with(key, ::Win32::Registry::KEY_READ | @registry.registry_system_architecture).and_yield(@reg_mock) + expect(@reg_mock).to receive(:each).and_yield("two", 2) + expect(@registry.type_matches?(key_path, value1)).to eq(false) end it "throws an exception if value does not exist" do - @registry.should_receive(:value_exists?).with(key_path, value1).and_return(false) - lambda{@registry.type_matches?(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegValueMissing) + expect(@registry).to receive(:value_exists?).with(key_path, value1).and_return(false) + expect{@registry.type_matches?(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegValueMissing) end end describe "type_matches!" do it "does nothing if the type_matches" do - @registry.should_receive(:type_matches?).with(key_path, value1).and_return(true) + expect(@registry).to receive(:type_matches?).with(key_path, value1).and_return(true) @registry.type_matches!(key_path, value1) end it "throws an exception if the type does not match" do - @registry.should_receive(:type_matches?).with(key_path, value1).and_return(false) - lambda{@registry.type_matches!(key_path, value1)}.should raise_error(Chef::Exceptions::Win32RegTypesMismatch) + expect(@registry).to receive(:type_matches?).with(key_path, value1).and_return(false) + expect{@registry.type_matches!(key_path, value1)}.to raise_error(Chef::Exceptions::Win32RegTypesMismatch) end end describe "keys_missing?" do it "returns true if the keys are missing" do - @registry.should_receive(:key_exists?).with(missing_key_path).and_return(false) - @registry.keys_missing?(key_path).should == true + expect(@registry).to receive(:key_exists?).with(missing_key_path).and_return(false) + expect(@registry.keys_missing?(key_path)).to eq(true) end it "returns false if no keys in the path are missing" do - @registry.should_receive(:key_exists?).with(missing_key_path).and_return(true) - @registry.keys_missing?(key_path).should == false + expect(@registry).to receive(:key_exists?).with(missing_key_path).and_return(true) + expect(@registry.keys_missing?(key_path)).to eq(false) end end end diff --git a/spec/unit/resource/conditional_action_not_nothing_spec.rb b/spec/unit/resource/conditional_action_not_nothing_spec.rb index 9f29de55f2..d140615cfc 100644 --- a/spec/unit/resource/conditional_action_not_nothing_spec.rb +++ b/spec/unit/resource/conditional_action_not_nothing_spec.rb @@ -27,7 +27,7 @@ describe Chef::Resource::ConditionalActionNotNothing do end it "indicates that resource convergence should not continue" do - expect(@conditional.continue?).to be_false + expect(@conditional.continue?).to be_falsey end end @@ -38,7 +38,7 @@ describe Chef::Resource::ConditionalActionNotNothing do end it "indicates that resource convergence should continue" do - expect(@conditional.continue?).to be_true + expect(@conditional.continue?).to be_truthy end end diff --git a/spec/unit/resource/conditional_spec.rb b/spec/unit/resource/conditional_spec.rb index cacac925b7..779c69425a 100644 --- a/spec/unit/resource/conditional_spec.rb +++ b/spec/unit/resource/conditional_spec.rb @@ -53,7 +53,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should continue" do - expect(@conditional.continue?).to be_true + expect(@conditional.continue?).to be_truthy end end @@ -64,7 +64,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should not continue" do - expect(@conditional.continue?).to be_false + expect(@conditional.continue?).to be_falsey end end @@ -75,7 +75,7 @@ describe Chef::Resource::Conditional do end it 'indicates that resource convergence should not continue' do - expect(@conditional.continue?).to be_false + expect(@conditional.continue?).to be_falsey end it 'should log a warning' do @@ -90,7 +90,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should continue" do - expect(@conditional.continue?).to be_true + expect(@conditional.continue?).to be_truthy end end @@ -100,7 +100,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should not continue" do - expect(@conditional.continue?).to be_false + expect(@conditional.continue?).to be_falsey end end end @@ -112,7 +112,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should not continue" do - expect(@conditional.continue?).to be_false + expect(@conditional.continue?).to be_falsey end end @@ -123,7 +123,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should continue" do - expect(@conditional.continue?).to be_true + expect(@conditional.continue?).to be_truthy end end @@ -134,7 +134,7 @@ describe Chef::Resource::Conditional do end it 'indicates that resource convergence should continue' do - expect(@conditional.continue?).to be_true + expect(@conditional.continue?).to be_truthy end it 'should log a warning' do @@ -149,7 +149,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should not continue" do - expect(@conditional.continue?).to be_false + expect(@conditional.continue?).to be_falsey end end @@ -159,7 +159,7 @@ describe Chef::Resource::Conditional do end it "indicates that resource convergence should continue" do - expect(@conditional.continue?).to be_true + expect(@conditional.continue?).to be_truthy end end end diff --git a/spec/unit/resource/deploy_spec.rb b/spec/unit/resource/deploy_spec.rb index 6592fae26c..0403a7ba6b 100644 --- a/spec/unit/resource/deploy_spec.rb +++ b/spec/unit/resource/deploy_spec.rb @@ -115,9 +115,9 @@ describe Chef::Resource::Deploy do end it "has a boolean attribute for svn_force_export defaulting to false" do - expect(@resource.svn_force_export).to be_false + expect(@resource.svn_force_export).to be_falsey @resource.svn_force_export true - expect(@resource.svn_force_export).to be_true + expect(@resource.svn_force_export).to be_truthy expect {@resource.svn_force_export(10053)}.to raise_error(ArgumentError) end diff --git a/spec/unit/resource/remote_file_spec.rb b/spec/unit/resource/remote_file_spec.rb index 14d2fb97bc..3731d1aee2 100644 --- a/spec/unit/resource/remote_file_spec.rb +++ b/spec/unit/resource/remote_file_spec.rb @@ -113,40 +113,40 @@ describe Chef::Resource::RemoteFile do describe "ftp_active_mode" do it "should accept a boolean for the ftp_active_mode object" do @resource.ftp_active_mode true - expect(@resource.ftp_active_mode).to be_true + expect(@resource.ftp_active_mode).to be_truthy end it "should default to false" do - expect(@resource.ftp_active_mode).to be_false + expect(@resource.ftp_active_mode).to be_falsey end end describe "conditional get options" do it "defaults to using etags and last modified" do - expect(@resource.use_etags).to be_true - expect(@resource.use_last_modified).to be_true + expect(@resource.use_etags).to be_truthy + expect(@resource.use_last_modified).to be_truthy end it "enable or disables etag and last modified options as a group" do @resource.use_conditional_get(false) - expect(@resource.use_etags).to be_false - expect(@resource.use_last_modified).to be_false + expect(@resource.use_etags).to be_falsey + expect(@resource.use_last_modified).to be_falsey @resource.use_conditional_get(true) - expect(@resource.use_etags).to be_true - expect(@resource.use_last_modified).to be_true + expect(@resource.use_etags).to be_truthy + expect(@resource.use_last_modified).to be_truthy end it "disables etags indivdually" do @resource.use_etags(false) - expect(@resource.use_etags).to be_false - expect(@resource.use_last_modified).to be_true + expect(@resource.use_etags).to be_falsey + expect(@resource.use_last_modified).to be_truthy end it "disables last modified individually" do @resource.use_last_modified(false) - expect(@resource.use_last_modified).to be_false - expect(@resource.use_etags).to be_true + expect(@resource.use_last_modified).to be_falsey + expect(@resource.use_etags).to be_truthy end end diff --git a/spec/unit/resource/scm_spec.rb b/spec/unit/resource/scm_spec.rb index daabdd03ba..72319277ab 100644 --- a/spec/unit/resource/scm_spec.rb +++ b/spec/unit/resource/scm_spec.rb @@ -110,22 +110,22 @@ describe Chef::Resource::Scm do it "takes a boolean for #enable_submodules" do @resource.enable_submodules true - expect(@resource.enable_submodules).to be_true + expect(@resource.enable_submodules).to be_truthy expect {@resource.enable_submodules "lolz"}.to raise_error(ArgumentError) end it "defaults to not enabling submodules" do - expect(@resource.enable_submodules).to be_false + expect(@resource.enable_submodules).to be_falsey end it "takes a boolean for #enable_checkout" do @resource.enable_checkout true - expect(@resource.enable_checkout).to be_true + expect(@resource.enable_checkout).to be_truthy expect {@resource.enable_checkout "lolz"}.to raise_error(ArgumentError) end it "defaults to enabling checkout" do - expect(@resource.enable_checkout).to be_true + expect(@resource.enable_checkout).to be_truthy end it "takes a string for the remote" do diff --git a/spec/unit/resource/subversion_spec.rb b/spec/unit/resource/subversion_spec.rb index 4cbca9be11..5cd5d0de80 100644 --- a/spec/unit/resource/subversion_spec.rb +++ b/spec/unit/resource/subversion_spec.rb @@ -62,6 +62,6 @@ describe Chef::Resource::Subversion do it "hides password from custom exception message" do @svn.svn_password "l33th4x0rpa$$w0rd" e = @svn.customize_exception(Chef::Exceptions::Exec.new "Exception with password #{@svn.svn_password}") - expect(e.message.include?(@svn.svn_password)).to be_false + expect(e.message.include?(@svn.svn_password)).to be_falsey end end diff --git a/spec/unit/resource_collection/resource_list_spec.rb b/spec/unit/resource_collection/resource_list_spec.rb index 641fe55c8d..1e6c477854 100644 --- a/spec/unit/resource_collection/resource_list_spec.rb +++ b/spec/unit/resource_collection/resource_list_spec.rb @@ -60,7 +60,7 @@ describe Chef::ResourceCollection::ResourceList do end it "should be empty by default" do - expect(resource_list.empty?).to be_true + expect(resource_list.empty?).to be_truthy end describe "when resources are inserted" do @@ -100,7 +100,7 @@ describe Chef::ResourceCollection::ResourceList do end it "should be able to check if the list is empty" do - expect(resource_list.empty?).to be_false + expect(resource_list.empty?).to be_falsey end end end diff --git a/spec/unit/resource_collection/resource_set_spec.rb b/spec/unit/resource_collection/resource_set_spec.rb index 8be31cd9f6..0e25934216 100644 --- a/spec/unit/resource_collection/resource_set_spec.rb +++ b/spec/unit/resource_collection/resource_set_spec.rb @@ -166,15 +166,15 @@ describe Chef::ResourceCollection::ResourceSet do describe "validate_lookup_spec!" do it "accepts a string of the form 'resource_type[resource_name]'" do - expect(collection.validate_lookup_spec!("resource_type[resource_name]")).to be_true + expect(collection.validate_lookup_spec!("resource_type[resource_name]")).to be_truthy end it "accepts a single-element :resource_type => 'resource_name' Hash" do - expect(collection.validate_lookup_spec!(:service => "apache2")).to be_true + expect(collection.validate_lookup_spec!(:service => "apache2")).to be_truthy end it "accepts a chef resource object" do - expect(collection.validate_lookup_spec!(zen_master)).to be_true + expect(collection.validate_lookup_spec!(zen_master)).to be_truthy end it "rejects a malformed query string" do diff --git a/spec/unit/resource_collection/stepable_iterator_spec.rb b/spec/unit/resource_collection/stepable_iterator_spec.rb index b649f8be6e..b34b7140fe 100644 --- a/spec/unit/resource_collection/stepable_iterator_spec.rb +++ b/spec/unit/resource_collection/stepable_iterator_spec.rb @@ -21,7 +21,7 @@ describe Chef::ResourceCollection::StepableIterator do CRSI = Chef::ResourceCollection::StepableIterator it "has an empty array for its collection by default" do - CRSI.new.collection.should == [] + expect(CRSI.new.collection).to eq([]) end describe "doing basic iteration" do @@ -31,8 +31,8 @@ describe Chef::ResourceCollection::StepableIterator do end it "re-initializes the instance with a collection" do - @iterator.collection.should equal(@simple_collection) - @iterator.size.should == 4 + expect(@iterator.collection).to equal(@simple_collection) + expect(@iterator.size).to eq(4) end it "iterates over the collection" do @@ -40,7 +40,7 @@ describe Chef::ResourceCollection::StepableIterator do @iterator.each do |int| sum += int end - sum.should == 10 + expect(sum).to eq(10) end it "iterates over the collection with each_index" do @@ -48,8 +48,8 @@ describe Chef::ResourceCollection::StepableIterator do @iterator.each_index do |idx| collected_by_index << @simple_collection[idx] end - collected_by_index.should == @simple_collection - collected_by_index.should_not equal(@simple_collection) + expect(collected_by_index).to eq(@simple_collection) + expect(collected_by_index).not_to equal(@simple_collection) end it "iterates over the collection with index and element" do @@ -57,7 +57,7 @@ describe Chef::ResourceCollection::StepableIterator do @iterator.each_with_index do |element, index| collected[index] = element end - collected.should == {0=>1, 1=>2, 2=>3, 3=>4} + expect(collected).to eq({0=>1, 1=>2, 2=>3, 3=>4}) end end @@ -76,49 +76,49 @@ describe Chef::ResourceCollection::StepableIterator do end it "allows the iteration to be paused" do - @snitch_var.should == 23 + expect(@snitch_var).to eq(23) end it "allows the iteration to be resumed" do - @snitch_var.should == 23 + expect(@snitch_var).to eq(23) @iterator.resume - @snitch_var.should == 42 + expect(@snitch_var).to eq(42) end it "allows iteration to be rewound" do @iterator.skip_back(2) @iterator.resume - @snitch_var.should == 23 + expect(@snitch_var).to eq(23) @iterator.resume - @snitch_var.should == 42 + expect(@snitch_var).to eq(42) end it "allows iteration to be fast forwarded" do @iterator.skip_forward @iterator.resume - @snitch_var.should == 23 + expect(@snitch_var).to eq(23) end it "allows iteration to be rewound" do @snitch_var = nil @iterator.rewind - @iterator.position.should == 0 + expect(@iterator.position).to eq(0) @iterator.resume - @snitch_var.should == 23 + expect(@snitch_var).to eq(23) end it "allows iteration to be stepped" do @snitch_var = nil @iterator.rewind @iterator.step - @iterator.position.should == 1 - @snitch_var.should == 23 + expect(@iterator.position).to eq(1) + expect(@snitch_var).to eq(23) end it "doesn't step if there are no more steps" do - @iterator.step.should == 3 - lambda {@iterator.step}.should_not raise_error - @iterator.step.should be_nil + expect(@iterator.step).to eq(3) + expect {@iterator.step}.not_to raise_error + expect(@iterator.step).to be_nil end it "allows the iteration to start by being stepped" do @@ -126,17 +126,17 @@ describe Chef::ResourceCollection::StepableIterator do @iterator = CRSI.for_collection(@collection) @iterator.iterate_on(:element) { |proc| proc.call } @iterator.step - @iterator.position.should == 1 - @snitch_var.should == 23 + expect(@iterator.position).to eq(1) + expect(@snitch_var).to eq(23) end it "should work correctly when elements are added to the collection during iteration" do @collection.insert(2, lambda { @snitch_var = 815}) @collection.insert(3, lambda { @iterator.pause }) @iterator.resume - @snitch_var.should == 815 + expect(@snitch_var).to eq(815) @iterator.resume - @snitch_var.should == 42 + expect(@snitch_var).to eq(42) end end diff --git a/spec/unit/resource_collection_spec.rb b/spec/unit/resource_collection_spec.rb index 5966fdd1f2..b43b012dfc 100644 --- a/spec/unit/resource_collection_spec.rb +++ b/spec/unit/resource_collection_spec.rb @@ -29,39 +29,39 @@ describe Chef::ResourceCollection do describe "initialize" do it "should return a Chef::ResourceCollection" do - rc.should be_kind_of(Chef::ResourceCollection) + expect(rc).to be_kind_of(Chef::ResourceCollection) end end describe "[]" do it "should accept Chef::Resources through [index]" do - lambda { rc[0] = resource }.should_not raise_error - lambda { rc[0] = "string" }.should raise_error(ArgumentError) + expect { rc[0] = resource }.not_to raise_error + expect { rc[0] = "string" }.to raise_error(ArgumentError) end it "should allow you to fetch Chef::Resources by position" do rc[0] = resource - rc[0].should eql(resource) + expect(rc[0]).to eql(resource) end end describe "push" do it "should accept Chef::Resources through pushing" do - lambda { rc.push(resource) }.should_not raise_error - lambda { rc.push("string") }.should raise_error(ArgumentError) + expect { rc.push(resource) }.not_to raise_error + expect { rc.push("string") }.to raise_error(ArgumentError) end end describe "<<" do it "should accept the << operator" do - lambda { rc << resource }.should_not raise_error + expect { rc << resource }.not_to raise_error end end describe "insert" do it "should accept only Chef::Resources" do - lambda { rc.insert(resource) }.should_not raise_error - lambda { rc.insert("string") }.should raise_error(ArgumentError) + expect { rc.insert(resource) }.not_to raise_error + expect { rc.insert("string") }.to raise_error(ArgumentError) end it "should accept named arguments in any order" do @@ -73,8 +73,8 @@ describe Chef::ResourceCollection do zmr = Chef::Resource::ZenMaster.new("there is no spoon") rc.insert(resource) rc.insert(zmr) - rc[0].should eql(resource) - rc[1].should eql(zmr) + expect(rc[0]).to eql(resource) + expect(rc[1]).to eql(zmr) end it "should insert resources to the middle of the collection if called while executing a run" do @@ -88,9 +88,9 @@ describe Chef::ResourceCollection do rc.insert(resource_to_inject) if resource == zmr end - rc[0].should eql(zmr) - rc[1].should eql(resource_to_inject) - rc[2].should eql(dummy) + expect(rc[0]).to eql(zmr) + expect(rc[1]).to eql(resource_to_inject) + expect(rc[2]).to eql(dummy) end end @@ -98,19 +98,19 @@ describe Chef::ResourceCollection do it "should allow you to iterate over every resource in the collection" do load_up_resources results = Array.new - lambda { + expect { rc.each do |r| results << r.name end - }.should_not raise_error + }.not_to raise_error results.each_index do |i| case i when 0 - results[i].should eql("dog") + expect(results[i]).to eql("dog") when 1 - results[i].should eql("cat") + expect(results[i]).to eql("cat") when 2 - results[i].should eql("monkey") + expect(results[i]).to eql("monkey") end end end @@ -120,19 +120,19 @@ describe Chef::ResourceCollection do it "should allow you to iterate over every resource by index" do load_up_resources results = Array.new - lambda { + expect { rc.each_index do |i| results << rc[i].name end - }.should_not raise_error + }.not_to raise_error results.each_index do |i| case i when 0 - results[i].should eql("dog") + expect(results[i]).to eql("dog") when 1 - results[i].should eql("cat") + expect(results[i]).to eql("cat") when 2 - results[i].should eql("monkey") + expect(results[i]).to eql("monkey") end end end @@ -142,23 +142,23 @@ describe Chef::ResourceCollection do it "should allow you to find resources by name via lookup" do zmr = Chef::Resource::ZenMaster.new("dog") rc << zmr - rc.lookup(zmr.to_s).should eql(zmr) + expect(rc.lookup(zmr.to_s)).to eql(zmr) zmr = Chef::Resource::ZenMaster.new("cat") rc[0] = zmr - rc.lookup(zmr).should eql(zmr) + expect(rc.lookup(zmr)).to eql(zmr) zmr = Chef::Resource::ZenMaster.new("monkey") rc.push(zmr) - rc.lookup(zmr).should eql(zmr) + expect(rc.lookup(zmr)).to eql(zmr) end it "should raise an exception if you send something strange to lookup" do - lambda { rc.lookup(:symbol) }.should raise_error(ArgumentError) + expect { rc.lookup(:symbol) }.to raise_error(ArgumentError) end it "should raise an exception if it cannot find a resource with lookup" do - lambda { rc.lookup("zen_master[dog]") }.should raise_error(Chef::Exceptions::ResourceNotFound) + expect { rc.lookup("zen_master[dog]") }.to raise_error(Chef::Exceptions::ResourceNotFound) end end @@ -166,81 +166,81 @@ describe Chef::ResourceCollection do it "should find a resource by symbol and name (:zen_master => monkey)" do load_up_resources - rc.resources(:zen_master => "monkey").name.should eql("monkey") + expect(rc.resources(:zen_master => "monkey").name).to eql("monkey") end it "should find a resource by symbol and array of names (:zen_master => [a,b])" do load_up_resources results = rc.resources(:zen_master => [ "monkey", "dog" ]) - results.length.should eql(2) + expect(results.length).to eql(2) check_by_names(results, "monkey", "dog") end it "should find resources of multiple kinds (:zen_master => a, :file => b)" do load_up_resources results = rc.resources(:zen_master => "monkey", :file => "something") - results.length.should eql(2) + expect(results.length).to eql(2) check_by_names(results, "monkey", "something") end it "should find a resource by string zen_master[a]" do load_up_resources - rc.resources("zen_master[monkey]").name.should eql("monkey") + expect(rc.resources("zen_master[monkey]").name).to eql("monkey") end it "should find resources by strings of zen_master[a,b]" do load_up_resources results = rc.resources("zen_master[monkey,dog]") - results.length.should eql(2) + expect(results.length).to eql(2) check_by_names(results, "monkey", "dog") end it "should find resources of multiple types by strings of zen_master[a]" do load_up_resources results = rc.resources("zen_master[monkey]", "file[something]") - results.length.should eql(2) + expect(results.length).to eql(2) check_by_names(results, "monkey", "something") end it "should raise an exception if you pass a bad name to resources" do - lambda { rc.resources("michael jackson") }.should raise_error(ArgumentError) + expect { rc.resources("michael jackson") }.to raise_error(ArgumentError) end it "should raise an exception if you pass something other than a string or hash to resource" do - lambda { rc.resources([Array.new]) }.should raise_error(ArgumentError) + expect { rc.resources([Array.new]) }.to raise_error(ArgumentError) end it "raises an error when attempting to find a resource that does not exist" do - lambda {rc.find("script[nonesuch]")}.should raise_error(Chef::Exceptions::ResourceNotFound) + expect {rc.find("script[nonesuch]")}.to raise_error(Chef::Exceptions::ResourceNotFound) end end describe "when validating a resource query object" do it "accepts a string of the form 'resource_type[resource_name]'" do - rc.validate_lookup_spec!("resource_type[resource_name]").should be_true + expect(rc.validate_lookup_spec!("resource_type[resource_name]")).to be_truthy end it "accepts a single-element :resource_type => 'resource_name' Hash" do - rc.validate_lookup_spec!(:service => "apache2").should be_true + expect(rc.validate_lookup_spec!(:service => "apache2")).to be_truthy end it "accepts a chef resource object" do res = Chef::Resource.new("foo", nil) - rc.validate_lookup_spec!(res).should be_true + expect(rc.validate_lookup_spec!(res)).to be_truthy end it "rejects a malformed query string" do - lambda do + expect do rc.validate_lookup_spec!("resource_type[missing-end-bracket") - end.should raise_error(Chef::Exceptions::InvalidResourceSpecification) + end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end it "rejects an argument that is not a String, Hash, or Chef::Resource" do - lambda do + expect do rc.validate_lookup_spec!(Object.new) - end.should raise_error(Chef::Exceptions::InvalidResourceSpecification) + end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end end @@ -248,8 +248,8 @@ describe Chef::ResourceCollection do describe "to_json" do it "should serialize to json" do json = rc.to_json - json.should =~ /json_class/ - json.should =~ /instance_vars/ + expect(json).to match(/json_class/) + expect(json).to match(/instance_vars/) end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -266,27 +266,27 @@ describe Chef::ResourceCollection do rc << resource json = Chef::JSONCompat.to_json(rc) s_rc = Chef::JSONCompat.from_json(json) - s_rc.should be_a_kind_of(Chef::ResourceCollection) - s_rc[0].name.should eql(resource.name) + expect(s_rc).to be_a_kind_of(Chef::ResourceCollection) + expect(s_rc[0].name).to eql(resource.name) end end describe "provides access to the raw resources array" do it "returns the resources via the all_resources method" do - rc.all_resources.should equal(rc.instance_variable_get(:@resource_list).instance_variable_get(:@resources)) + expect(rc.all_resources).to equal(rc.instance_variable_get(:@resource_list).instance_variable_get(:@resources)) end end describe "provides access to stepable iterator" do it "returns the iterator object" do rc.instance_variable_get(:@resource_list).instance_variable_set(:@iterator, :fooboar) - rc.iterator.should == :fooboar + expect(rc.iterator).to eq(:fooboar) end end def check_by_names(results, *names) names.each do |res_name| - results.detect{ |res| res.name == res_name }.should_not eql(nil) + expect(results.detect{ |res| res.name == res_name }).not_to eql(nil) end end diff --git a/spec/unit/resource_reporter_spec.rb b/spec/unit/resource_reporter_spec.rb index 1a89cbdce1..4f3a085584 100644 --- a/spec/unit/resource_reporter_spec.rb +++ b/spec/unit/resource_reporter_spec.rb @@ -37,13 +37,13 @@ describe Chef::ResourceReporter do @node = Chef::Node.new @node.name("spitfire") @rest_client = double("Chef::REST (mock)") - @rest_client.stub(:post_rest).and_return(true) + allow(@rest_client).to receive(:post_rest).and_return(true) @resource_reporter = Chef::ResourceReporter.new(@rest_client) @new_resource = Chef::Resource::File.new("/tmp/a-file.txt") @cookbook_name = "monkey" @new_resource.cookbook_name = @cookbook_name @cookbook_version = double("Cookbook::Version", :version => "1.2.3") - @new_resource.stub(:cookbook_version).and_return(@cookbook_version) + allow(@new_resource).to receive(:cookbook_version).and_return(@cookbook_version) @current_resource = Chef::Resource::File.new("/tmp/a-file.txt") @start_time = Time.new @end_time = Time.new + 20 @@ -51,25 +51,25 @@ describe Chef::ResourceReporter do @run_context = Chef::RunContext.new(@node, {}, @events) @run_status = Chef::RunStatus.new(@node, @events) @run_id = @run_status.run_id - Time.stub(:now).and_return(@start_time, @end_time) + allow(Time).to receive(:now).and_return(@start_time, @end_time) end context "when first created" do it "has no updated resources" do - @resource_reporter.should have(0).updated_resources + expect(@resource_reporter.updated_resources.size).to eq(0) end it "reports a successful run" do - @resource_reporter.status.should == "success" + expect(@resource_reporter.status).to eq("success") end it "assumes the resource history feature is supported" do - @resource_reporter.reporting_enabled?.should be_true + expect(@resource_reporter.reporting_enabled?).to be_truthy end it "should have no error_descriptions" do - @resource_reporter.error_descriptions.should eq({}) + expect(@resource_reporter.error_descriptions).to eq({}) # @resource_reporter.error_descriptions.should be_empty # @resource_reporter.should have(0).error_descriptions end @@ -82,16 +82,16 @@ describe Chef::ResourceReporter do end it "reports a successful run" do - pending "refactor how node gets set." - @resource_reporter.status.should == "success" + skip "refactor how node gets set." + expect(@resource_reporter.status).to eq("success") end end context "when chef fails" do before do - @rest_client.stub(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}"); - @rest_client.stub(:raw_http_request).and_return({"result"=>"ok"}); - @rest_client.stub(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); + allow(@rest_client).to receive(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}"); + allow(@rest_client).to receive(:raw_http_request).and_return({"result"=>"ok"}); + allow(@rest_client).to receive(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); end @@ -103,11 +103,11 @@ describe Chef::ResourceReporter do end it "sets the run status to 'failure'" do - @resource_reporter.status.should == "failure" + expect(@resource_reporter.status).to eq("failure") end it "keeps the exception data" do - @resource_reporter.exception.should == @exception + expect(@resource_reporter.exception).to eq(@exception) end end @@ -121,12 +121,12 @@ describe Chef::ResourceReporter do end it "collects the resource as an updated resource" do - @resource_reporter.should have(1).updated_resources + expect(@resource_reporter.updated_resources.size).to eq(1) end it "collects the desired state of the resource" do update_record = @resource_reporter.updated_resources.first - update_record.new_resource.should == @new_resource + expect(update_record.new_resource).to eq(@new_resource) end end @@ -145,7 +145,7 @@ describe Chef::ResourceReporter do end it "has no updated resources" do - @resource_reporter.should have(0).updated_resources + expect(@resource_reporter.updated_resources.size).to eq(0) end end @@ -158,17 +158,17 @@ describe Chef::ResourceReporter do end it "collects the updated resource" do - @resource_reporter.should have(1).updated_resources + expect(@resource_reporter.updated_resources.size).to eq(1) end it "collects the old state of the resource" do update_record = @resource_reporter.updated_resources.first - update_record.current_resource.should == @current_resource + expect(update_record.current_resource).to eq(@current_resource) end it "collects the new state of the resource" do update_record = @resource_reporter.updated_resources.first - update_record.new_resource.should == @new_resource + expect(update_record.new_resource).to eq(@new_resource) end context "and a subsequent resource fails before loading current resource" do @@ -182,12 +182,12 @@ describe Chef::ResourceReporter do it "collects the desired state of the failed resource" do failed_resource_update = @resource_reporter.updated_resources.last - failed_resource_update.new_resource.should == @next_new_resource + expect(failed_resource_update.new_resource).to eq(@next_new_resource) end it "does not have the current state of the failed resource" do failed_resource_update = @resource_reporter.updated_resources.last - failed_resource_update.current_resource.should be_nil + expect(failed_resource_update.current_resource).to be_nil end end end @@ -208,7 +208,7 @@ describe Chef::ResourceReporter do end it "does not collect data about the nested resource" do - @resource_reporter.should have(1).updated_resources + expect(@resource_reporter.updated_resources.size).to eq(1) end end @@ -224,7 +224,7 @@ describe Chef::ResourceReporter do end it "does not collect data about the nested resource" do - @resource_reporter.should have(1).updated_resources + expect(@resource_reporter.updated_resources.size).to eq(1) end end @@ -237,17 +237,17 @@ describe Chef::ResourceReporter do end it "collects the resource as an updated resource" do - @resource_reporter.should have(1).updated_resources + expect(@resource_reporter.updated_resources.size).to eq(1) end it "collects the desired state of the resource" do update_record = @resource_reporter.updated_resources.first - update_record.new_resource.should == @new_resource + expect(update_record.new_resource).to eq(@new_resource) end it "collects the current state of the resource" do update_record = @resource_reporter.updated_resources.first - update_record.current_resource.should == @current_resource + expect(update_record.current_resource).to eq(@current_resource) end end @@ -257,9 +257,9 @@ describe Chef::ResourceReporter do describe "when generating a report for the server" do before do - @rest_client.stub(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}"); - @rest_client.stub(:raw_http_request).and_return({"result"=>"ok"}); - @rest_client.stub(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); + allow(@rest_client).to receive(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}"); + allow(@rest_client).to receive(:raw_http_request).and_return({"result"=>"ok"}); + allow(@rest_client).to receive(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); @resource_reporter.run_started(@run_status) end @@ -268,8 +268,8 @@ describe Chef::ResourceReporter do context "the new_resource name and id are nil" do before do @bad_resource = Chef::Resource::File.new("/tmp/nameless_file.txt") - @bad_resource.stub(:name).and_return(nil) - @bad_resource.stub(:identity).and_return(nil) + allow(@bad_resource).to receive(:name).and_return(nil) + allow(@bad_resource).to receive(:identity).and_return(nil) @resource_reporter.resource_action_start(@bad_resource, :create) @resource_reporter.resource_current_state_loaded(@bad_resource, :create, @current_resource) @resource_reporter.resource_updated(@bad_resource, :create) @@ -280,19 +280,19 @@ describe Chef::ResourceReporter do end it "resource_name in prepared_run_data is a string" do - @first_update_report["name"].class.should == String + expect(@first_update_report["name"].class).to eq(String) end it "resource_id in prepared_run_data is a string" do - @first_update_report["id"].class.should == String + expect(@first_update_report["id"].class).to eq(String) end end context "the new_resource name and id are hashes" do before do @bad_resource = Chef::Resource::File.new("/tmp/filename_as_hash.txt") - @bad_resource.stub(:name).and_return({:foo=>:bar}) - @bad_resource.stub(:identity).and_return({:foo=>:bar}) + allow(@bad_resource).to receive(:name).and_return({:foo=>:bar}) + allow(@bad_resource).to receive(:identity).and_return({:foo=>:bar}) @resource_reporter.resource_action_start(@bad_resource, :create) @resource_reporter.resource_current_state_loaded(@bad_resource, :create, @current_resource) @resource_reporter.resource_updated(@bad_resource, :create) @@ -309,11 +309,11 @@ describe Chef::ResourceReporter do # => "{:foo=>:bar}" # Hence checking for the class instead of the actual value. it "resource_name in prepared_run_data is a string" do - @first_update_report["name"].class.should == String + expect(@first_update_report["name"].class).to eq(String) end it "resource_id in prepared_run_data is a string" do - @first_update_report["id"].class.should == String + expect(@first_update_report["id"].class).to eq(String) end end end @@ -360,73 +360,73 @@ describe Chef::ResourceReporter do end it "includes the run's status" do - @report.should have_key("status") + expect(@report).to have_key("status") end it "includes a list of updated resources" do - @report.should have_key("resources") + expect(@report).to have_key("resources") end it "includes an updated resource's type" do - @first_update_report.should have_key("type") + expect(@first_update_report).to have_key("type") end it "includes an updated resource's initial state" do - @first_update_report["before"].should == current_resource.state + expect(@first_update_report["before"]).to eq(current_resource.state) end it "includes an updated resource's final state" do - @first_update_report["after"].should == new_resource.state + expect(@first_update_report["after"]).to eq(new_resource.state) end it "includes the resource's name" do - @first_update_report["name"].should == new_resource.name + expect(@first_update_report["name"]).to eq(new_resource.name) end it "includes the resource's id attribute" do - @first_update_report["id"].should == new_resource.identity + expect(@first_update_report["id"]).to eq(new_resource.identity) end it "includes the elapsed time for the resource to converge" do # TODO: API takes integer number of milliseconds as a string. This # should be an int. - @first_update_report.should have_key("duration") - @first_update_report["duration"].to_i.should be_within(100).of(0) + expect(@first_update_report).to have_key("duration") + expect(@first_update_report["duration"].to_i).to be_within(100).of(0) end it "includes the action executed by the resource" do # TODO: rename as "action" - @first_update_report["result"].should == "create" + expect(@first_update_report["result"]).to eq("create") end it "includes the cookbook name of the resource" do - @first_update_report.should have_key("cookbook_name") - @first_update_report["cookbook_name"].should == @cookbook_name + expect(@first_update_report).to have_key("cookbook_name") + expect(@first_update_report["cookbook_name"]).to eq(@cookbook_name) end it "includes the cookbook version of the resource" do - @first_update_report.should have_key("cookbook_version") - @first_update_report["cookbook_version"].should == "1.2.3" + expect(@first_update_report).to have_key("cookbook_version") + expect(@first_update_report["cookbook_version"]).to eq("1.2.3") end it "includes the total resource count" do - @report.should have_key("total_res_count") - @report["total_res_count"].should == "1" + expect(@report).to have_key("total_res_count") + expect(@report["total_res_count"]).to eq("1") end it "includes the data hash" do - @report.should have_key("data") - @report["data"].should == {} + expect(@report).to have_key("data") + expect(@report["data"]).to eq({}) end it "includes the run_list" do - @report.should have_key("run_list") - @report["run_list"].should == Chef::JSONCompat.to_json(@run_status.node.run_list) + expect(@report).to have_key("run_list") + expect(@report["run_list"]).to eq(Chef::JSONCompat.to_json(@run_status.node.run_list)) end it "includes the end_time" do - @report.should have_key("end_time") - @report["end_time"].should == @run_status.end_time.to_s + expect(@report).to have_key("end_time") + expect(@report["end_time"]).to eq(@run_status.end_time.to_s) end end @@ -442,8 +442,8 @@ describe Chef::ResourceReporter do let(:new_resource) do resource = Chef::Resource::RegistryKey.new('Wubba\Lubba\Dub\Dubs') resource.values([ { :name => 'rick', :type => :binary, :data => 255.chr * 1 } ]) - resource.stub(:cookbook_name).and_return(@cookbook_name) - resource.stub(:cookbook_version).and_return(@cookbook_version) + allow(resource).to receive(:cookbook_name).and_return(@cookbook_name) + allow(resource).to receive(:cookbook_version).and_return(@cookbook_version) resource end @@ -463,33 +463,33 @@ describe Chef::ResourceReporter do @node = Chef::Node.new @node.name("spitfire") @exception = ArgumentError.new - @exception.stub(:inspect).and_return("Net::HTTPServerException") - @exception.stub(:message).and_return("Object not found") - @exception.stub(:backtrace).and_return(@backtrace) + allow(@exception).to receive(:inspect).and_return("Net::HTTPServerException") + allow(@exception).to receive(:message).and_return("Object not found") + allow(@exception).to receive(:backtrace).and_return(@backtrace) @resource_reporter.run_list_expand_failed(@node, @exception) @resource_reporter.run_failed(@exception) @report = @resource_reporter.prepare_run_data end it "includes the exception type in the event data" do - @report.should have_key("data") - @report["data"]["exception"].should have_key("class") - @report["data"]["exception"]["class"].should == "Net::HTTPServerException" + expect(@report).to have_key("data") + expect(@report["data"]["exception"]).to have_key("class") + expect(@report["data"]["exception"]["class"]).to eq("Net::HTTPServerException") end it "includes the exception message in the event data" do - @report["data"]["exception"].should have_key("message") - @report["data"]["exception"]["message"].should == "Object not found" + expect(@report["data"]["exception"]).to have_key("message") + expect(@report["data"]["exception"]["message"]).to eq("Object not found") end it "includes the exception trace in the event data" do - @report["data"]["exception"].should have_key("backtrace") - @report["data"]["exception"]["backtrace"].should == Chef::JSONCompat.to_json(@backtrace) + expect(@report["data"]["exception"]).to have_key("backtrace") + expect(@report["data"]["exception"]["backtrace"]).to eq(Chef::JSONCompat.to_json(@backtrace)) end it "includes the error inspector output in the event data" do - @report["data"]["exception"].should have_key("description") - @report["data"]["exception"]["description"].should include({"title"=>"Error expanding the run_list:", "sections"=>[{"Unexpected Error:" => "ArgumentError: Object not found"}]}) + expect(@report["data"]["exception"]).to have_key("description") + expect(@report["data"]["exception"]["description"]).to include({"title"=>"Error expanding the run_list:", "sections"=>[{"Unexpected Error:" => "ArgumentError: Object not found"}]}) end end @@ -509,39 +509,39 @@ describe Chef::ResourceReporter do end it "includes an updated resource's initial state" do - @first_update_report["before"].should == @current_resource.state + expect(@first_update_report["before"]).to eq(@current_resource.state) end it "includes an updated resource's final state" do - @first_update_report["after"].should == @new_resource.state + expect(@first_update_report["after"]).to eq(@new_resource.state) end it "includes the resource's name" do - @first_update_report["name"].should == @new_resource.name + expect(@first_update_report["name"]).to eq(@new_resource.name) end it "includes the resource's id attribute" do - @first_update_report["id"].should == @new_resource.identity + expect(@first_update_report["id"]).to eq(@new_resource.identity) end it "includes the elapsed time for the resource to converge" do # TODO: API takes integer number of milliseconds as a string. This # should be an int. - @first_update_report.should have_key("duration") - @first_update_report["duration"].to_i.should be_within(100).of(0) + expect(@first_update_report).to have_key("duration") + expect(@first_update_report["duration"].to_i).to be_within(100).of(0) end it "includes the action executed by the resource" do # TODO: rename as "action" - @first_update_report["result"].should == "create" + expect(@first_update_report["result"]).to eq("create") end it "does not include a cookbook name for the resource" do - @first_update_report.should_not have_key("cookbook_name") + expect(@first_update_report).not_to have_key("cookbook_name") end it "does not include a cookbook version for the resource" do - @first_update_report.should_not have_key("cookbook_version") + expect(@first_update_report).not_to have_key("cookbook_version") end end @@ -562,13 +562,13 @@ describe Chef::ResourceReporter do end it "sets before to {} instead of nil" do - @first_update_report.should have_key("before") - @first_update_report['before'].should eq({}) + expect(@first_update_report).to have_key("before") + expect(@first_update_report['before']).to eq({}) end it "sets after to {} instead of 'Running'" do - @first_update_report.should have_key("after") - @first_update_report['after'].should eq({}) + expect(@first_update_report).to have_key("after") + expect(@first_update_report['after']).to eq({}) end end @@ -585,7 +585,7 @@ describe Chef::ResourceReporter do # 404 getting the run_id @response = Net::HTTPNotFound.new("a response body", "404", "Not Found") @error = Net::HTTPServerException.new("404 message", @response) - @rest_client.should_receive(:post_rest). + expect(@rest_client).to receive(:post_rest). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). @@ -594,17 +594,17 @@ describe Chef::ResourceReporter do it "assumes the feature is not enabled" do @resource_reporter.run_started(@run_status) - @resource_reporter.reporting_enabled?.should be_false + expect(@resource_reporter.reporting_enabled?).to be_falsey end it "does not send a resource report to the server" do @resource_reporter.run_started(@run_status) - @rest_client.should_not_receive(:post_rest) + expect(@rest_client).not_to receive(:post_rest) @resource_reporter.run_completed(@node) end it "prints an error about the 404" do - Chef::Log.should_receive(:debug).with(/404/) + expect(Chef::Log).to receive(:debug).with(/404/) @resource_reporter.run_started(@run_status) end @@ -615,7 +615,7 @@ describe Chef::ResourceReporter do # 500 getting the run_id @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error") @error = Net::HTTPServerException.new("500 message", @response) - @rest_client.should_receive(:post_rest). + expect(@rest_client).to receive(:post_rest). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). and_raise(@error) @@ -623,17 +623,17 @@ describe Chef::ResourceReporter do it "assumes the feature is not enabled" do @resource_reporter.run_started(@run_status) - @resource_reporter.reporting_enabled?.should be_false + expect(@resource_reporter.reporting_enabled?).to be_falsey end it "does not send a resource report to the server" do @resource_reporter.run_started(@run_status) - @rest_client.should_not_receive(:post_rest) + expect(@rest_client).not_to receive(:post_rest) @resource_reporter.run_completed(@node) end it "prints an error about the error" do - Chef::Log.should_receive(:info).with(/500/) + expect(Chef::Log).to receive(:info).with(/500/) @resource_reporter.run_started(@run_status) end end @@ -645,7 +645,7 @@ describe Chef::ResourceReporter do # 500 getting the run_id @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error") @error = Net::HTTPServerException.new("500 message", @response) - @rest_client.should_receive(:post_rest). + expect(@rest_client).to receive(:post_rest). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). and_raise(@error) @@ -656,17 +656,17 @@ describe Chef::ResourceReporter do end it "fails the run and prints an message about the error" do - Chef::Log.should_receive(:error).with(/500/) - lambda { + expect(Chef::Log).to receive(:error).with(/500/) + expect { @resource_reporter.run_started(@run_status) - }.should raise_error(Net::HTTPServerException) + }.to raise_error(Net::HTTPServerException) end end context "after creating the run history document" do before do response = {"uri"=>"https://example.com/reports/nodes/spitfire/runs/@run_id"} - @rest_client.should_receive(:post_rest). + expect(@rest_client).to receive(:post_rest). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). and_return(response) @@ -674,7 +674,7 @@ describe Chef::ResourceReporter do end it "creates a run document on the server at the start of the run" do - @resource_reporter.run_id.should == @run_id + expect(@resource_reporter.run_id).to eq(@run_id) end it "updates the run document with resource updates at the end of the run" do @@ -683,25 +683,25 @@ describe Chef::ResourceReporter do @resource_reporter.resource_current_state_loaded(@new_resource, :create, @current_resource) @resource_reporter.resource_updated(@new_resource, :create) - @resource_reporter.stub(:end_time).and_return(@end_time) + allow(@resource_reporter).to receive(:end_time).and_return(@end_time) @expected_data = @resource_reporter.prepare_run_data post_url = "https://chef_server/example_url" response = {"result"=>"ok"} - @rest_client.should_receive(:create_url). + expect(@rest_client).to receive(:create_url). with("reports/nodes/spitfire/runs/#{@run_id}"). ordered. and_return(post_url) - @rest_client.should_receive(:raw_http_request).ordered do |method, url, headers, data| - method.should eq(:POST) - url.should eq(post_url) - headers.should eq({'Content-Encoding' => 'gzip', + expect(@rest_client).to receive(:raw_http_request).ordered do |method, url, headers, data| + expect(method).to eq(:POST) + expect(url).to eq(post_url) + expect(headers).to eq({'Content-Encoding' => 'gzip', 'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION }) data_stream = Zlib::GzipReader.new(StringIO.new(data)) data = data_stream.read - data.should eq(Chef::JSONCompat.to_json(@expected_data)) + expect(data).to eq(Chef::JSONCompat.to_json(@expected_data)) response end @@ -714,7 +714,7 @@ describe Chef::ResourceReporter do @enable_reporting_url_fatals = Chef::Config[:enable_reporting_url_fatals] Chef::Config[:enable_reporting_url_fatals] = true # this call doesn't matter for this context - @rest_client.stub(:create_url) + allow(@rest_client).to receive(:create_url) end after do @@ -724,8 +724,8 @@ describe Chef::ResourceReporter do it "should log 4xx errors" do response = Net::HTTPClientError.new("forbidden", "403", "Forbidden") error = Net::HTTPServerException.new("403 message", response) - @rest_client.stub(:raw_http_request).and_raise(error) - Chef::Log.should_receive(:error).with(/403/) + allow(@rest_client).to receive(:raw_http_request).and_raise(error) + expect(Chef::Log).to receive(:error).with(/403/) @resource_reporter.post_reporting_data end @@ -733,26 +733,26 @@ describe Chef::ResourceReporter do it "should log error 5xx errors" do response = Net::HTTPServerError.new("internal error", "500", "Internal Server Error") error = Net::HTTPFatalError.new("500 message", response) - @rest_client.stub(:raw_http_request).and_raise(error) - Chef::Log.should_receive(:error).with(/500/) + allow(@rest_client).to receive(:raw_http_request).and_raise(error) + expect(Chef::Log).to receive(:error).with(/500/) @resource_reporter.post_reporting_data end it "should log if a socket error happens" do - @rest_client.stub(:raw_http_request).and_raise(SocketError.new("test socket error")) - Chef::Log.should_receive(:error).with(/test socket error/) + allow(@rest_client).to receive(:raw_http_request).and_raise(SocketError.new("test socket error")) + expect(Chef::Log).to receive(:error).with(/test socket error/) @resource_reporter.post_reporting_data end it "should raise if an unkwown error happens" do - @rest_client.stub(:raw_http_request).and_raise(Exception.new) + allow(@rest_client).to receive(:raw_http_request).and_raise(Exception.new) - lambda { + expect { @resource_reporter.post_reporting_data - }.should raise_error(Exception) + }.to raise_error(Exception) end end end diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb index 2163cf181e..bb02d91b23 100644 --- a/spec/unit/resource_spec.rb +++ b/spec/unit/resource_spec.rb @@ -39,33 +39,33 @@ describe Chef::Resource do it "adds an entry to a list of subclasses" do subclass = Class.new(Chef::Resource) - Chef::Resource.resource_classes.should include(subclass) + expect(Chef::Resource.resource_classes).to include(subclass) end it "keeps track of subclasses of subclasses" do subclass = Class.new(Chef::Resource) subclass_of_subclass = Class.new(subclass) - Chef::Resource.resource_classes.should include(subclass_of_subclass) + expect(Chef::Resource.resource_classes).to include(subclass_of_subclass) end end describe "when declaring the identity attribute" do it "has no identity attribute by default" do - Chef::Resource.identity_attr.should be_nil + expect(Chef::Resource.identity_attr).to be_nil end it "sets an identity attribute" do resource_class = Class.new(Chef::Resource) resource_class.identity_attr(:path) - resource_class.identity_attr.should == :path + expect(resource_class.identity_attr).to eq(:path) end it "inherits an identity attribute from a superclass" do resource_class = Class.new(Chef::Resource) resource_subclass = Class.new(resource_class) resource_class.identity_attr(:package_name) - resource_subclass.identity_attr.should == :package_name + expect(resource_subclass.identity_attr).to eq(:package_name) end it "overrides the identity attribute from a superclass when the identity attr is set" do @@ -73,7 +73,7 @@ describe Chef::Resource do resource_subclass = Class.new(resource_class) resource_class.identity_attr(:package_name) resource_subclass.identity_attr(:something_else) - resource_subclass.identity_attr.should == :something_else + expect(resource_subclass.identity_attr).to eq(:something_else) end end @@ -85,7 +85,7 @@ describe Chef::Resource do # Would rather force identity attributes to be set for everything, # but that's not plausible for back compat reasons. it "uses the name as the identity" do - @resource_sans_id.identity.should == "my-name" + expect(@resource_sans_id.identity).to eq("my-name") end end @@ -101,26 +101,26 @@ describe Chef::Resource do end it "gives the value of its identity attribute" do - @file_resource.identity.should == "/tmp/foo.txt" + expect(@file_resource.identity).to eq("/tmp/foo.txt") end end describe "when declaring state attributes" do it "has no state_attrs by default" do - Chef::Resource.state_attrs.should be_empty + expect(Chef::Resource.state_attrs).to be_empty end it "sets a list of state attributes" do resource_class = Class.new(Chef::Resource) resource_class.state_attrs(:checksum, :owner, :group, :mode) - resource_class.state_attrs.should =~ [:checksum, :owner, :group, :mode] + expect(resource_class.state_attrs).to match_array([:checksum, :owner, :group, :mode]) end it "inherits state attributes from the superclass" do resource_class = Class.new(Chef::Resource) resource_subclass = Class.new(resource_class) resource_class.state_attrs(:checksum, :owner, :group, :mode) - resource_subclass.state_attrs.should =~ [:checksum, :owner, :group, :mode] + expect(resource_subclass.state_attrs).to match_array([:checksum, :owner, :group, :mode]) end it "combines inherited state attributes with non-inherited state attributes" do @@ -128,7 +128,7 @@ describe Chef::Resource do resource_subclass = Class.new(resource_class) resource_class.state_attrs(:checksum, :owner) resource_subclass.state_attrs(:group, :mode) - resource_subclass.state_attrs.should =~ [:checksum, :owner, :group, :mode] + expect(resource_subclass.state_attrs).to match_array([:checksum, :owner, :group, :mode]) end end @@ -154,11 +154,11 @@ describe Chef::Resource do it "describes its state" do resource_state = @file_resource.state - resource_state.keys.should =~ [:checksum, :owner, :group, :mode] - resource_state[:checksum].should == "abc123" - resource_state[:owner].should == "root" - resource_state[:group].should == "wheel" - resource_state[:mode].should == "0644" + expect(resource_state.keys).to match_array([:checksum, :owner, :group, :mode]) + expect(resource_state[:checksum]).to eq("abc123") + expect(resource_state[:owner]).to eq("root") + expect(resource_state[:group]).to eq("wheel") + expect(resource_state[:mode]).to eq("0644") end end @@ -175,39 +175,39 @@ describe Chef::Resource do it "should load the attributes of a prior resource" do @resource.load_prior_resource(@resource.resource_name, @resource.name) - @resource.supports.should == { :funky => true } + expect(@resource.supports).to eq({ :funky => true }) end it "should not inherit the action from the prior resource" do @resource.load_prior_resource(@resource.resource_name, @resource.name) - @resource.action.should_not == @prior_resource.action + expect(@resource.action).not_to eq(@prior_resource.action) end end describe "name" do it "should have a name" do - @resource.name.should eql("funk") + expect(@resource.name).to eql("funk") end it "should let you set a new name" do @resource.name "monkey" - @resource.name.should eql("monkey") + expect(@resource.name).to eql("monkey") end it "should not be valid without a name" do - lambda { @resource.name false }.should raise_error(ArgumentError) + expect { @resource.name false }.to raise_error(ArgumentError) end it "should always have a string for name" do - lambda { @resource.name Hash.new }.should raise_error(ArgumentError) + expect { @resource.name Hash.new }.to raise_error(ArgumentError) end end describe "noop" do it "should accept true or false for noop" do - lambda { @resource.noop true }.should_not raise_error - lambda { @resource.noop false }.should_not raise_error - lambda { @resource.noop "eat it" }.should raise_error(ArgumentError) + expect { @resource.noop true }.not_to raise_error + expect { @resource.noop false }.not_to raise_error + expect { @resource.noop "eat it" }.to raise_error(ArgumentError) end end @@ -215,48 +215,48 @@ describe Chef::Resource do it "should make notified resources appear in the actions hash" do @run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") @resource.notifies :reload, @run_context.resource_collection.find(:zen_master => "coffee") - @resource.delayed_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}.should_not be_nil + expect(@resource.delayed_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}).not_to be_nil end it "should make notified resources be capable of acting immediately" do @run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") @resource.notifies :reload, @run_context.resource_collection.find(:zen_master => "coffee"), :immediate - @resource.immediate_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}.should_not be_nil + expect(@resource.immediate_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}).not_to be_nil end it "should raise an exception if told to act in other than :delay or :immediate(ly)" do @run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") - lambda { + expect { @resource.notifies :reload, @run_context.resource_collection.find(:zen_master => "coffee"), :someday - }.should raise_error(ArgumentError) + }.to raise_error(ArgumentError) end it "should allow multiple notified resources appear in the actions hash" do @run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") @resource.notifies :reload, @run_context.resource_collection.find(:zen_master => "coffee") - @resource.delayed_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}.should_not be_nil + expect(@resource.delayed_notifications.detect{|e| e.resource.name == "coffee" && e.action == :reload}).not_to be_nil @run_context.resource_collection << Chef::Resource::ZenMaster.new("beans") @resource.notifies :reload, @run_context.resource_collection.find(:zen_master => "beans") - @resource.delayed_notifications.detect{|e| e.resource.name == "beans" && e.action == :reload}.should_not be_nil + expect(@resource.delayed_notifications.detect{|e| e.resource.name == "beans" && e.action == :reload}).not_to be_nil end it "creates a notification for a resource that is not yet in the resource collection" do @resource.notifies(:restart, :service => 'apache') expected_notification = Chef::Resource::Notification.new({:service => "apache"}, :restart, @resource) - @resource.delayed_notifications.should include(expected_notification) + expect(@resource.delayed_notifications).to include(expected_notification) end it "notifies another resource immediately" do @resource.notifies_immediately(:restart, :service => 'apache') expected_notification = Chef::Resource::Notification.new({:service => "apache"}, :restart, @resource) - @resource.immediate_notifications.should include(expected_notification) + expect(@resource.immediate_notifications).to include(expected_notification) end it "notifies a resource to take action at the end of the chef run" do @resource.notifies_delayed(:restart, :service => "apache") expected_notification = Chef::Resource::Notification.new({:service => "apache"}, :restart, @resource) - @resource.delayed_notifications.should include(expected_notification) + expect(@resource.delayed_notifications).to include(expected_notification) end end @@ -265,76 +265,76 @@ describe Chef::Resource do @run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = @run_context.resource_collection.find(:zen_master => "coffee") @resource.subscribes :reload, zr - zr.delayed_notifications.detect{|e| e.resource.name == "funk" && e.action == :reload}.should_not be_nil + expect(zr.delayed_notifications.detect{|e| e.resource.name == "funk" && e.action == :reload}).not_to be_nil end it "should make resources appear in the actions hash of subscribed nodes" do @run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = @run_context.resource_collection.find(:zen_master => "coffee") @resource.subscribes :reload, zr - zr.delayed_notifications.detect{|e| e.resource.name == @resource.name && e.action == :reload}.should_not be_nil + expect(zr.delayed_notifications.detect{|e| e.resource.name == @resource.name && e.action == :reload}).not_to be_nil @run_context.resource_collection << Chef::Resource::ZenMaster.new("bean") zrb = @run_context.resource_collection.find(:zen_master => "bean") zrb.subscribes :reload, zr - zr.delayed_notifications.detect{|e| e.resource.name == @resource.name && e.action == :reload}.should_not be_nil + expect(zr.delayed_notifications.detect{|e| e.resource.name == @resource.name && e.action == :reload}).not_to be_nil end it "should make subscribed resources be capable of acting immediately" do @run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = @run_context.resource_collection.find(:zen_master => "coffee") @resource.subscribes :reload, zr, :immediately - zr.immediate_notifications.detect{|e| e.resource.name == @resource.name && e.action == :reload}.should_not be_nil + expect(zr.immediate_notifications.detect{|e| e.resource.name == @resource.name && e.action == :reload}).not_to be_nil end end describe "defined_at" do it "should correctly parse source_line on unix-like operating systems" do @resource.source_line = "/some/path/to/file.rb:80:in `wombat_tears'" - @resource.defined_at.should == "/some/path/to/file.rb line 80" + expect(@resource.defined_at).to eq("/some/path/to/file.rb line 80") end it "should correctly parse source_line on Windows" do @resource.source_line = "C:/some/path/to/file.rb:80 in 1`wombat_tears'" - @resource.defined_at.should == "C:/some/path/to/file.rb line 80" + expect(@resource.defined_at).to eq("C:/some/path/to/file.rb line 80") end it "should include the cookbook and recipe when it knows it" do @resource.source_line = "/some/path/to/file.rb:80:in `wombat_tears'" @resource.recipe_name = "wombats" @resource.cookbook_name = "animals" - @resource.defined_at.should == "animals::wombats line 80" + expect(@resource.defined_at).to eq("animals::wombats line 80") end it "should recognize dynamically defined resources" do - @resource.defined_at.should == "dynamically defined" + expect(@resource.defined_at).to eq("dynamically defined") end end describe "to_s" do it "should become a string like resource_name[name]" do zm = Chef::Resource::ZenMaster.new("coffee") - zm.to_s.should eql("zen_master[coffee]") + expect(zm.to_s).to eql("zen_master[coffee]") end end describe "is" do it "should return the arguments passed with 'is'" do zm = Chef::Resource::ZenMaster.new("coffee") - zm.is("one", "two", "three").should == %w|one two three| + expect(zm.is("one", "two", "three")).to eq(%w|one two three|) end it "should allow arguments preceeded by is to methods" do @resource.noop(@resource.is(true)) - @resource.noop.should eql(true) + expect(@resource.noop).to eql(true) end end describe "to_json" do it "should serialize to json" do json = @resource.to_json - json.should =~ /json_class/ - json.should =~ /instance_vars/ + expect(json).to match(/json_class/) + expect(json).to match(/instance_vars/) end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -350,9 +350,9 @@ describe Chef::Resource do :noop, :ignore_failure, :name, :source_line, :action, :retries, :retry_delay, :elapsed_time, :default_guard_interpreter, :guard_interpreter, :sensitive ] - (hash.keys - expected_keys).should == [] - (expected_keys - hash.keys).should == [] - hash[:name].should eql("funk") + expect(hash.keys - expected_keys).to eq([]) + expect(expected_keys - hash.keys).to eq([]) + expect(hash[:name]).to eql("funk") end end @@ -360,8 +360,8 @@ describe Chef::Resource do it "should deserialize itself from json" do json = Chef::JSONCompat.to_json(@resource) serialized_node = Chef::JSONCompat.from_json(json) - serialized_node.should be_a_kind_of(Chef::Resource) - serialized_node.name.should eql(@resource.name) + expect(serialized_node).to be_a_kind_of(Chef::Resource) + expect(serialized_node.name).to eql(@resource.name) end end @@ -369,27 +369,27 @@ describe Chef::Resource do it "should allow you to set what features this resource supports" do support_hash = { :one => :two } @resource.supports(support_hash) - @resource.supports.should eql(support_hash) + expect(@resource.supports).to eql(support_hash) end it "should return the current value of supports" do - @resource.supports.should == {} + expect(@resource.supports).to eq({}) end end describe "ignore_failure" do it "should default to throwing an error if a provider fails for a resource" do - @resource.ignore_failure.should == false + expect(@resource.ignore_failure).to eq(false) end it "should allow you to set whether a provider should throw exceptions with ignore_failure" do @resource.ignore_failure(true) - @resource.ignore_failure.should == true + expect(@resource.ignore_failure).to eq(true) end it "should allow you to epic_fail" do @resource.epic_fail(true) - @resource.epic_fail.should == true + expect(@resource.epic_fail).to eq(true) end end @@ -404,21 +404,21 @@ describe Chef::Resource do end it "should default to not retrying if a provider fails for a resource" do - @retriable_resource.retries.should == 0 + expect(@retriable_resource.retries).to eq(0) end it "should allow you to set how many retries a provider should attempt after a failure" do @retriable_resource.retries(2) - @retriable_resource.retries.should == 2 + expect(@retriable_resource.retries).to eq(2) end it "should default to a retry delay of 2 seconds" do - @retriable_resource.retry_delay.should == 2 + expect(@retriable_resource.retry_delay).to eq(2) end it "should allow you to set the retry delay" do @retriable_resource.retry_delay(10) - @retriable_resource.retry_delay.should == 10 + expect(@retriable_resource.retry_delay).to eq(10) end it "should keep given value of retries intact after the provider fails for a resource" do @@ -426,29 +426,29 @@ describe Chef::Resource do @retriable_resource.retry_delay(0) # No need to wait. provider = Chef::Provider::SnakeOil.new(@retriable_resource, @run_context) - Chef::Provider::SnakeOil.stub(:new).and_return(provider) - provider.stub(:action_purr).and_raise + allow(Chef::Provider::SnakeOil).to receive(:new).and_return(provider) + allow(provider).to receive(:action_purr).and_raise - @retriable_resource.should_receive(:sleep).exactly(3).times + expect(@retriable_resource).to receive(:sleep).exactly(3).times expect { @retriable_resource.run_action(:purr) }.to raise_error - @retriable_resource.retries.should == 3 + expect(@retriable_resource.retries).to eq(3) end end describe "setting the base provider class for the resource" do it "defaults to Chef::Provider for the base class" do - Chef::Resource.provider_base.should == Chef::Provider + expect(Chef::Resource.provider_base).to eq(Chef::Provider) end it "allows the base provider to be overriden by a " do - ResourceTestHarness.provider_base.should == Chef::Provider::Package + expect(ResourceTestHarness.provider_base).to eq(Chef::Provider::Package) end end it "runs an action by finding its provider, loading the current resource and then running the action" do - pending + skip end describe "when updated by a provider" do @@ -457,11 +457,11 @@ describe Chef::Resource do end it "records that it was updated" do - @resource.should be_updated + expect(@resource).to be_updated end it "records that the last action updated the resource" do - @resource.should be_updated_by_last_action + expect(@resource).to be_updated_by_last_action end describe "and then run again without being updated" do @@ -470,11 +470,11 @@ describe Chef::Resource do end it "reports that it is updated" do - @resource.should be_updated + expect(@resource).to be_updated end it "reports that it was not updated by the last action" do - @resource.should_not be_updated_by_last_action + expect(@resource).not_to be_updated_by_last_action end end @@ -498,10 +498,10 @@ describe Chef::Resource do it "runs runs an only_if when one is given" do snitch_variable = nil @resource.only_if { snitch_variable = true } - @resource.only_if.first.positivity.should == :only_if + expect(@resource.only_if.first.positivity).to eq(:only_if) #Chef::Mixin::Command.should_receive(:only_if).with(true, {}).and_return(false) @resource.run_action(:purr) - snitch_variable.should be_true + expect(snitch_variable).to be_truthy end it "runs multiple only_if conditionals" do @@ -509,25 +509,25 @@ describe Chef::Resource do @resource.only_if { snitch_var1 = 1 } @resource.only_if { snitch_var2 = 2 } @resource.run_action(:purr) - snitch_var1.should == 1 - snitch_var2.should == 2 + expect(snitch_var1).to eq(1) + expect(snitch_var2).to eq(2) end it "accepts command options for only_if conditionals" do - Chef::Resource::Conditional.any_instance.should_receive(:evaluate_command).at_least(1).times + expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_command).at_least(1).times @resource.only_if("true", :cwd => '/tmp') - @resource.only_if.first.command_opts.should == {:cwd => '/tmp'} + expect(@resource.only_if.first.command_opts).to eq({:cwd => '/tmp'}) @resource.run_action(:purr) end it "runs not_if as a command when it is a string" do - Chef::Resource::Conditional.any_instance.should_receive(:evaluate_command).at_least(1).times + expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_command).at_least(1).times @resource.not_if "pwd" @resource.run_action(:purr) end it "runs not_if as a block when it is a ruby block" do - Chef::Resource::Conditional.any_instance.should_receive(:evaluate_block).at_least(1).times + expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_block).at_least(1).times @resource.not_if { puts 'foo' } @resource.run_action(:purr) end @@ -540,7 +540,7 @@ describe Chef::Resource do it "accepts command options for not_if conditionals" do @resource.not_if("pwd" , :cwd => '/tmp') - @resource.not_if.first.command_opts.should == {:cwd => '/tmp'} + expect(@resource.not_if.first.command_opts).to eq({:cwd => '/tmp'}) end it "accepts multiple not_if conditionals" do @@ -548,27 +548,27 @@ describe Chef::Resource do @resource.not_if {snitch_var1 = nil} @resource.not_if {snitch_var2 = false} @resource.run_action(:purr) - snitch_var1.should be_nil - snitch_var2.should be_false + expect(snitch_var1).to be_nil + expect(snitch_var2).to be_falsey end it "reports 0 elapsed time if actual elapsed time is < 0" do expected = Time.now - Time.stub(:now).and_return(expected, expected - 1) + allow(Time).to receive(:now).and_return(expected, expected - 1) @resource.run_action(:purr) - @resource.elapsed_time.should == 0 + expect(@resource.elapsed_time).to eq(0) end describe "guard_interpreter attribute" do let(:resource) { @resource } it "should be set to :default by default" do - resource.guard_interpreter.should == :default + expect(resource.guard_interpreter).to eq(:default) end it "if set to :default should return :default when read" do resource.guard_interpreter(:default) - resource.guard_interpreter.should == :default + expect(resource.guard_interpreter).to eq(:default) end it "should raise Chef::Exceptions::ValidationFailed on an attempt to set the guard_interpreter attribute to something other than a Symbol" do @@ -576,7 +576,7 @@ describe Chef::Resource do end it "should not raise an exception when setting the guard interpreter attribute to a Symbol" do - Chef::GuardInterpreter::ResourceGuardInterpreter.stub(:new).and_return(nil) + allow(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:new).and_return(nil) expect { resource.guard_interpreter(:command_dot_com) }.not_to raise_error end end @@ -588,63 +588,63 @@ describe Chef::Resource do end it "should return false by default" do - @resource.should_skip?(:purr).should be_false + expect(@resource.should_skip?(:purr)).to be_falsey end it "should return false when only_if is met" do @resource.only_if { true } - @resource.should_skip?(:purr).should be_false + expect(@resource.should_skip?(:purr)).to be_falsey end it "should return true when only_if is not met" do @resource.only_if { false } - @resource.should_skip?(:purr).should be_true + expect(@resource.should_skip?(:purr)).to be_truthy end it "should return true when not_if is met" do @resource.not_if { true } - @resource.should_skip?(:purr).should be_true + expect(@resource.should_skip?(:purr)).to be_truthy end it "should return false when not_if is not met" do @resource.not_if { false } - @resource.should_skip?(:purr).should be_false + expect(@resource.should_skip?(:purr)).to be_falsey end it "should return true when only_if is met but also not_if is met" do @resource.only_if { true } @resource.not_if { true } - @resource.should_skip?(:purr).should be_true + expect(@resource.should_skip?(:purr)).to be_truthy end it "should return true when one of multiple only_if's is not met" do @resource.only_if { true } @resource.only_if { false } @resource.only_if { true } - @resource.should_skip?(:purr).should be_true + expect(@resource.should_skip?(:purr)).to be_truthy end it "should return true when one of multiple not_if's is met" do @resource.not_if { false } @resource.not_if { true } @resource.not_if { false } - @resource.should_skip?(:purr).should be_true + expect(@resource.should_skip?(:purr)).to be_truthy end it "should return true when action is :nothing" do - @resource.should_skip?(:nothing).should be_true + expect(@resource.should_skip?(:nothing)).to be_truthy end it "should return true when action is :nothing ignoring only_if/not_if conditionals" do @resource.only_if { true } @resource.not_if { false } - @resource.should_skip?(:nothing).should be_true + expect(@resource.should_skip?(:nothing)).to be_truthy end it "should print \"skipped due to action :nothing\" message for doc formatter when action is :nothing" do fdoc = Chef::Formatters.new(:doc, STDOUT, STDERR) - @run_context.stub(:events).and_return(fdoc) - fdoc.should_receive(:puts).with(" (skipped due to action :nothing)", anything()) + allow(@run_context).to receive(:events).and_return(fdoc) + expect(fdoc).to receive(:puts).with(" (skipped due to action :nothing)", anything()) @resource.should_skip?(:nothing) end @@ -664,7 +664,7 @@ describe Chef::Resource do @resource1.only_if { snitch_var1 = 1 } @resource1.not_if { snitch_var1 = 2 } @resource1.run_action(:nothing) - snitch_var1.should == 0 + expect(snitch_var1).to eq(0) end it "should run only_if/not_if conditionals when notified to run another action (CHEF-972)" do @@ -685,8 +685,8 @@ describe Chef::Resource do @run_context.resource_collection << @resource2 @runner.converge - snitch_var1.should == 1 - snitch_var2.should == 2 + expect(snitch_var1).to eq(1) + expect(snitch_var2).to eq(2) end end @@ -750,10 +750,10 @@ describe Chef::Resource do describe "resource_for_node" do it "returns a resource by short_name and node" do - Chef::Resource.resource_for_node(:dinobot, @node).should eql(Grimlock) + expect(Chef::Resource.resource_for_node(:dinobot, @node)).to eql(Grimlock) end it "returns a resource by short_name if nothing else matches" do - Chef::Resource.resource_for_node(:soundwave, @node).should eql(Soundwave) + expect(Chef::Resource.resource_for_node(:soundwave, @node)).to eql(Soundwave) end end @@ -765,30 +765,30 @@ describe Chef::Resource do it "creates a delayed notification when timing is not specified" do @resource.notifies(:run, "execute[foo]") - @run_context.delayed_notification_collection.should have(1).notifications + expect(@run_context.delayed_notification_collection.size).to eq(1) end it "creates a delayed notification when :delayed is not specified" do @resource.notifies(:run, "execute[foo]", :delayed) - @run_context.delayed_notification_collection.should have(1).notifications + expect(@run_context.delayed_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediate is specified" do @resource.notifies(:run, "execute[foo]", :immediate) - @run_context.immediate_notification_collection.should have(1).notifications + expect(@run_context.immediate_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediately is specified" do @resource.notifies(:run, "execute[foo]", :immediately) - @run_context.immediate_notification_collection.should have(1).notifications + expect(@run_context.immediate_notification_collection.size).to eq(1) end describe "with a syntax error in the resource spec" do it "raises an exception immmediately" do - lambda do + expect do @resource.notifies(:run, "typo[missing-closing-bracket") - end.should raise_error(Chef::Exceptions::InvalidResourceSpecification) + end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end end end @@ -800,22 +800,22 @@ describe Chef::Resource do it "creates a delayed notification when timing is not specified" do @resource.notifies(:run, @notified_resource) - @run_context.delayed_notification_collection.should have(1).notifications + expect(@run_context.delayed_notification_collection.size).to eq(1) end it "creates a delayed notification when :delayed is not specified" do @resource.notifies(:run, @notified_resource, :delayed) - @run_context.delayed_notification_collection.should have(1).notifications + expect(@run_context.delayed_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediate is specified" do @resource.notifies(:run, @notified_resource, :immediate) - @run_context.immediate_notification_collection.should have(1).notifications + expect(@run_context.immediate_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediately is specified" do @resource.notifies(:run, @notified_resource, :immediately) - @run_context.immediate_notification_collection.should have(1).notifications + expect(@run_context.immediate_notification_collection.size).to eq(1) end end @@ -837,19 +837,19 @@ describe Chef::Resource do end it "set to false by default" do - @resource.sensitive.should be_false + expect(@resource.sensitive).to be_falsey end it "when set to false should show compiled resource for failed resource" do expect { @resource_file.run_action(@action) }.to raise_error { |err| - compiled_resource_data(@resource_file, @action, err).should match 'path "/nonexistent/CHEF-5098/file"' + expect(compiled_resource_data(@resource_file, @action, err)).to match 'path "/nonexistent/CHEF-5098/file"' } end it "when set to true should show compiled resource for failed resource" do @resource_file.sensitive true expect { @resource_file.run_action(@action) }.to raise_error { |err| - compiled_resource_data(@resource_file, @action, err).should eql("suppressed sensitive resource output") + expect(compiled_resource_data(@resource_file, @action, err)).to eql("suppressed sensitive resource output") } end @@ -862,34 +862,34 @@ describe Chef::Resource::Notification do end it "has a resource to be notified" do - @notification.resource.should == :service_apache + expect(@notification.resource).to eq(:service_apache) end it "has an action to take on the service" do - @notification.action.should == :restart + expect(@notification.action).to eq(:restart) end it "has a notifying resource" do - @notification.notifying_resource.should == :template_httpd_conf + expect(@notification.notifying_resource).to eq(:template_httpd_conf) end it "is a duplicate of another notification with the same target resource and action" do other = Chef::Resource::Notification.new(:service_apache, :restart, :sync_web_app_code) - @notification.duplicates?(other).should be_true + expect(@notification.duplicates?(other)).to be_truthy end it "is not a duplicate of another notification if the actions differ" do other = Chef::Resource::Notification.new(:service_apache, :enable, :install_apache) - @notification.duplicates?(other).should be_false + expect(@notification.duplicates?(other)).to be_falsey end it "is not a duplicate of another notification if the target resources differ" do other = Chef::Resource::Notification.new(:service_sshd, :restart, :template_httpd_conf) - @notification.duplicates?(other).should be_false + expect(@notification.duplicates?(other)).to be_falsey end it "raises an ArgumentError if you try to check a non-ducktype object for duplication" do - lambda {@notification.duplicates?(:not_a_notification)}.should raise_error(ArgumentError) + expect {@notification.duplicates?(:not_a_notification)}.to raise_error(ArgumentError) end it "takes no action to resolve a resource reference that doesn't need to be resolved" do @@ -900,7 +900,7 @@ describe Chef::Resource::Notification do @resource_collection = Chef::ResourceCollection.new # would raise an error since the resource is not in the collection @notification.resolve_resource_reference(@resource_collection) - @notification.resource.should == @keyboard_cat + expect(@notification.resource).to eq(@keyboard_cat) end it "resolves a lazy reference to a resource" do @@ -911,7 +911,7 @@ describe Chef::Resource::Notification do @long_cat = Chef::Resource::Cat.new("long_cat") @notification.notifying_resource = @long_cat @notification.resolve_resource_reference(@resource_collection) - @notification.resource.should == @keyboard_cat + expect(@notification.resource).to eq(@keyboard_cat) end it "resolves a lazy reference to its notifying resource" do @@ -922,7 +922,7 @@ describe Chef::Resource::Notification do @resource_collection = Chef::ResourceCollection.new @resource_collection << @long_cat @notification.resolve_resource_reference(@resource_collection) - @notification.notifying_resource.should == @long_cat + expect(@notification.notifying_resource).to eq(@long_cat) end it "resolves lazy references to both its resource and its notifying resource" do @@ -934,8 +934,8 @@ describe Chef::Resource::Notification do @long_cat = Chef::Resource::Cat.new("long_cat") @resource_collection << @long_cat @notification.resolve_resource_reference(@resource_collection) - @notification.resource.should == @keyboard_cat - @notification.notifying_resource.should == @long_cat + expect(@notification.resource).to eq(@keyboard_cat) + expect(@notification.notifying_resource).to eq(@long_cat) end it "raises a RuntimeError if you try to reference multiple resources" do @@ -947,7 +947,7 @@ describe Chef::Resource::Notification do @resource_collection << @cheez_cat @long_cat = Chef::Resource::Cat.new("long_cat") @notification.notifying_resource = @long_cat - lambda {@notification.resolve_resource_reference(@resource_collection)}.should raise_error(RuntimeError) + expect {@notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) end it "raises a RuntimeError if you try to reference multiple notifying resources" do @@ -959,7 +959,7 @@ describe Chef::Resource::Notification do @resource_collection << @cheez_cat @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") @notification.resource = @keyboard_cat - lambda {@notification.resolve_resource_reference(@resource_collection)}.should raise_error(RuntimeError) + expect {@notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) end it "raises a RuntimeError if it can't find a resource in the resource collection when resolving a lazy reference" do @@ -969,7 +969,7 @@ describe Chef::Resource::Notification do @resource_collection << @cheez_cat @long_cat = Chef::Resource::Cat.new("long_cat") @notification.notifying_resource = @long_cat - lambda {@notification.resolve_resource_reference(@resource_collection)}.should raise_error(RuntimeError) + expect {@notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) end it "raises a RuntimeError if it can't find a notifying resource in the resource collection when resolving a lazy reference" do @@ -979,7 +979,7 @@ describe Chef::Resource::Notification do @resource_collection << @cheez_cat @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") @notification.resource = @keyboard_cat - lambda {@notification.resolve_resource_reference(@resource_collection)}.should raise_error(RuntimeError) + expect {@notification.resolve_resource_reference(@resource_collection)}.to raise_error(RuntimeError) end it "raises an ArgumentError if improper syntax is used in the lazy reference to its resource" do @@ -989,7 +989,7 @@ describe Chef::Resource::Notification do @resource_collection << @keyboard_cat @long_cat = Chef::Resource::Cat.new("long_cat") @notification.notifying_resource = @long_cat - lambda {@notification.resolve_resource_reference(@resource_collection)}.should raise_error(ArgumentError) + expect {@notification.resolve_resource_reference(@resource_collection)}.to raise_error(ArgumentError) end it "raises an ArgumentError if improper syntax is used in the lazy reference to its notifying resource" do @@ -999,7 +999,7 @@ describe Chef::Resource::Notification do @resource_collection << @long_cat @keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") @notification.resource = @keyboard_cat - lambda {@notification.resolve_resource_reference(@resource_collection)}.should raise_error(ArgumentError) + expect {@notification.resolve_resource_reference(@resource_collection)}.to raise_error(ArgumentError) end # Create test to resolve lazy references to both notifying resource and dest. resource diff --git a/spec/unit/rest/auth_credentials_spec.rb b/spec/unit/rest/auth_credentials_spec.rb index 477da0faec..3465156b90 100644 --- a/spec/unit/rest/auth_credentials_spec.rb +++ b/spec/unit/rest/auth_credentials_spec.rb @@ -62,18 +62,18 @@ describe Chef::REST::AuthCredentials do end it "has a client name" do - @auth_credentials.client_name.should == "client-name" + expect(@auth_credentials.client_name).to eq("client-name") end it "loads the private key when initialized with the path to the key" do - @auth_credentials.key.should respond_to(:private_encrypt) - @auth_credentials.key.to_s.should == KEY_DOT_PEM + expect(@auth_credentials.key).to respond_to(:private_encrypt) + expect(@auth_credentials.key.to_s).to eq(KEY_DOT_PEM) end describe "when loading the private key" do it "strips extra whitespace before checking the key" do key_file_fixture = CHEF_SPEC_DATA + '/ssl/private_key_with_whitespace.pem' - lambda {Chef::REST::AuthCredentials.new("client-name", @key_file_fixture)}.should_not raise_error + expect {Chef::REST::AuthCredentials.new("client-name", @key_file_fixture)}.not_to raise_error end end @@ -84,19 +84,19 @@ describe Chef::REST::AuthCredentials do end it "generates signature headers for the request" do - Time.stub(:now).and_return(@request_time) + allow(Time).to receive(:now).and_return(@request_time) actual = @auth_credentials.signature_headers(@request_params) - actual["HOST"].should == "localhost" - actual["X-OPS-AUTHORIZATION-1"].should == "kBssX1ENEwKtNYFrHElN9vYGWS7OeowepN9EsYc9csWfh8oUovryPKDxytQ/" - actual["X-OPS-AUTHORIZATION-2"].should == "Wc2/nSSyxdWJjjfHzrE+YrqNQTaArOA7JkAf5p75eTUonCWcvNPjFrZVgKGS" - actual["X-OPS-AUTHORIZATION-3"].should == "yhzHJQh+lcVA9wwARg5Hu9q+ddS8xBOdm3Vp5atl5NGHiP0loiigMYvAvzPO" - actual["X-OPS-AUTHORIZATION-4"].should == "r9853eIxwYMhn5hLGhAGFQznJbE8+7F/lLU5Zmk2t2MlPY8q3o1Q61YD8QiJ" - actual["X-OPS-AUTHORIZATION-5"].should == "M8lIt53ckMyUmSU0DDURoiXLVkE9mag/6Yq2tPNzWq2AdFvBqku9h2w+DY5k" - actual["X-OPS-AUTHORIZATION-6"].should == "qA5Rnzw5rPpp3nrWA9jKkPw4Wq3+4ufO2Xs6w7GCjA==" - actual["X-OPS-CONTENT-HASH"].should == "1tuzs5XKztM1ANrkGNPah6rW9GY=" - actual["X-OPS-SIGN"].should =~ %r{(version=1\.0)|(algorithm=sha1;version=1.0;)} - actual["X-OPS-TIMESTAMP"].should == "2010-04-10T17:34:20Z" - actual["X-OPS-USERID"].should == "client-name" + expect(actual["HOST"]).to eq("localhost") + expect(actual["X-OPS-AUTHORIZATION-1"]).to eq("kBssX1ENEwKtNYFrHElN9vYGWS7OeowepN9EsYc9csWfh8oUovryPKDxytQ/") + expect(actual["X-OPS-AUTHORIZATION-2"]).to eq("Wc2/nSSyxdWJjjfHzrE+YrqNQTaArOA7JkAf5p75eTUonCWcvNPjFrZVgKGS") + expect(actual["X-OPS-AUTHORIZATION-3"]).to eq("yhzHJQh+lcVA9wwARg5Hu9q+ddS8xBOdm3Vp5atl5NGHiP0loiigMYvAvzPO") + expect(actual["X-OPS-AUTHORIZATION-4"]).to eq("r9853eIxwYMhn5hLGhAGFQznJbE8+7F/lLU5Zmk2t2MlPY8q3o1Q61YD8QiJ") + expect(actual["X-OPS-AUTHORIZATION-5"]).to eq("M8lIt53ckMyUmSU0DDURoiXLVkE9mag/6Yq2tPNzWq2AdFvBqku9h2w+DY5k") + expect(actual["X-OPS-AUTHORIZATION-6"]).to eq("qA5Rnzw5rPpp3nrWA9jKkPw4Wq3+4ufO2Xs6w7GCjA==") + expect(actual["X-OPS-CONTENT-HASH"]).to eq("1tuzs5XKztM1ANrkGNPah6rW9GY=") + expect(actual["X-OPS-SIGN"]).to match(%r{(version=1\.0)|(algorithm=sha1;version=1.0;)}) + expect(actual["X-OPS-TIMESTAMP"]).to eq("2010-04-10T17:34:20Z") + expect(actual["X-OPS-USERID"]).to eq("client-name") end @@ -110,13 +110,13 @@ describe Chef::REST::AuthCredentials do end it "generates the correct signature for version 1.1" do - Time.stub(:now).and_return(@request_time) + allow(Time).to receive(:now).and_return(@request_time) actual = @auth_credentials.signature_headers(@request_params) - actual["HOST"].should == "localhost" - actual["X-OPS-CONTENT-HASH"].should == "1tuzs5XKztM1ANrkGNPah6rW9GY=" - actual["X-OPS-SIGN"].should == "algorithm=sha1;version=1.1;" - actual["X-OPS-TIMESTAMP"].should == "2010-04-10T17:34:20Z" - actual["X-OPS-USERID"].should == "client-name" + expect(actual["HOST"]).to eq("localhost") + expect(actual["X-OPS-CONTENT-HASH"]).to eq("1tuzs5XKztM1ANrkGNPah6rW9GY=") + expect(actual["X-OPS-SIGN"]).to eq("algorithm=sha1;version=1.1;") + expect(actual["X-OPS-TIMESTAMP"]).to eq("2010-04-10T17:34:20Z") + expect(actual["X-OPS-USERID"]).to eq("client-name") # mixlib-authN will test the actual signature stuff for each version of # the protocol so we won't test it again here. @@ -143,63 +143,63 @@ describe Chef::REST::RESTRequest do end it "stores the url it was created with" do - @request.url.should == @url + expect(@request.url).to eq(@url) end it "stores the HTTP method" do - @request.method.should == :POST + expect(@request.method).to eq(:POST) end it "adds the chef version header" do - @request.headers.should == @headers.merge("X-Chef-Version" => ::Chef::VERSION) + expect(@request.headers).to eq(@headers.merge("X-Chef-Version" => ::Chef::VERSION)) end describe "configuring the HTTP request" do it "configures GET requests" do @req_body = nil rest_req = new_request(:GET) - rest_req.http_request.should be_a_kind_of(Net::HTTP::Get) - rest_req.http_request.path.should == "/?q=chef_is_awesome" - rest_req.http_request.body.should be_nil + expect(rest_req.http_request).to be_a_kind_of(Net::HTTP::Get) + expect(rest_req.http_request.path).to eq("/?q=chef_is_awesome") + expect(rest_req.http_request.body).to be_nil end it "configures POST requests, including the body" do - @request.http_request.should be_a_kind_of(Net::HTTP::Post) - @request.http_request.path.should == "/?q=chef_is_awesome" - @request.http_request.body.should == @req_body + expect(@request.http_request).to be_a_kind_of(Net::HTTP::Post) + expect(@request.http_request.path).to eq("/?q=chef_is_awesome") + expect(@request.http_request.body).to eq(@req_body) end it "configures PUT requests, including the body" do rest_req = new_request(:PUT) - rest_req.http_request.should be_a_kind_of(Net::HTTP::Put) - rest_req.http_request.path.should == "/?q=chef_is_awesome" - rest_req.http_request.body.should == @req_body + expect(rest_req.http_request).to be_a_kind_of(Net::HTTP::Put) + expect(rest_req.http_request.path).to eq("/?q=chef_is_awesome") + expect(rest_req.http_request.body).to eq(@req_body) end it "configures DELETE requests" do rest_req = new_request(:DELETE) - rest_req.http_request.should be_a_kind_of(Net::HTTP::Delete) - rest_req.http_request.path.should == "/?q=chef_is_awesome" - rest_req.http_request.body.should be_nil + expect(rest_req.http_request).to be_a_kind_of(Net::HTTP::Delete) + expect(rest_req.http_request.path).to eq("/?q=chef_is_awesome") + expect(rest_req.http_request.body).to be_nil end it "configures HTTP basic auth" do @url = URI.parse("http://homie:theclown@chef.example.com:4000/?q=chef_is_awesome") rest_req = new_request(:GET) - rest_req.http_request.to_hash["authorization"].should == ["Basic aG9taWU6dGhlY2xvd24="] + expect(rest_req.http_request.to_hash["authorization"]).to eq(["Basic aG9taWU6dGhlY2xvd24="]) end end describe "configuring the HTTP client" do it "configures the HTTP client for the host and port" do http_client = new_request.http_client - http_client.address.should == "chef.example.com" - http_client.port.should == 4000 + expect(http_client.address).to eq("chef.example.com") + expect(http_client.port).to eq(4000) end it "configures the HTTP client with the read timeout set in the config file" do Chef::Config[:rest_timeout] = 9001 - new_request.http_client.read_timeout.should == 9001 + expect(new_request.http_client.read_timeout).to eq(9001) end describe "for proxy" do @@ -226,21 +226,21 @@ describe Chef::REST::RESTRequest do describe "with :no_proxy nil" do it "configures the proxy address and port when using http scheme" do http_client = new_request.http_client - http_client.proxy?.should == true - http_client.proxy_address.should == "proxy.example.com" - http_client.proxy_port.should == 3128 - http_client.proxy_user.should be_nil - http_client.proxy_pass.should be_nil + expect(http_client.proxy?).to eq(true) + expect(http_client.proxy_address).to eq("proxy.example.com") + expect(http_client.proxy_port).to eq(3128) + expect(http_client.proxy_user).to be_nil + expect(http_client.proxy_pass).to be_nil end it "configures the proxy address and port when using https scheme" do @url.scheme = "https" http_client = new_request.http_client - http_client.proxy?.should == true - http_client.proxy_address.should == "sproxy.example.com" - http_client.proxy_port.should == 3129 - http_client.proxy_user.should be_nil - http_client.proxy_pass.should be_nil + expect(http_client.proxy?).to eq(true) + expect(http_client.proxy_address).to eq("sproxy.example.com") + expect(http_client.proxy_port).to eq(3129) + expect(http_client.proxy_user).to be_nil + expect(http_client.proxy_pass).to be_nil end end @@ -251,21 +251,21 @@ describe Chef::REST::RESTRequest do it "does not configure the proxy address and port when using http scheme" do http_client = new_request.http_client - http_client.proxy?.should == false - http_client.proxy_address.should be_nil - http_client.proxy_port.should be_nil - http_client.proxy_user.should be_nil - http_client.proxy_pass.should be_nil + expect(http_client.proxy?).to eq(false) + expect(http_client.proxy_address).to be_nil + expect(http_client.proxy_port).to be_nil + expect(http_client.proxy_user).to be_nil + expect(http_client.proxy_pass).to be_nil end it "does not configure the proxy address and port when using https scheme" do @url.scheme = "https" http_client = new_request.http_client - http_client.proxy?.should == false - http_client.proxy_address.should be_nil - http_client.proxy_port.should be_nil - http_client.proxy_user.should be_nil - http_client.proxy_pass.should be_nil + expect(http_client.proxy?).to eq(false) + expect(http_client.proxy_address).to be_nil + expect(http_client.proxy_port).to be_nil + expect(http_client.proxy_user).to be_nil + expect(http_client.proxy_pass).to be_nil end end @@ -282,17 +282,17 @@ describe Chef::REST::RESTRequest do it "configures the proxy user and pass when using http scheme" do http_client = new_request.http_client - http_client.proxy?.should == true - http_client.proxy_user.should == "homie" - http_client.proxy_pass.should == "theclown" + expect(http_client.proxy?).to eq(true) + expect(http_client.proxy_user).to eq("homie") + expect(http_client.proxy_pass).to eq("theclown") end it "does not configure the proxy user and pass when using https scheme" do @url.scheme = "https" http_client = new_request.http_client - http_client.proxy?.should == true - http_client.proxy_user.should be_nil - http_client.proxy_pass.should be_nil + expect(http_client.proxy?).to eq(true) + expect(http_client.proxy_user).to be_nil + expect(http_client.proxy_pass).to be_nil end end @@ -309,17 +309,17 @@ describe Chef::REST::RESTRequest do it "does not configure the proxy user and pass when using http scheme" do http_client = new_request.http_client - http_client.proxy?.should == true - http_client.proxy_user.should be_nil - http_client.proxy_pass.should be_nil + expect(http_client.proxy?).to eq(true) + expect(http_client.proxy_user).to be_nil + expect(http_client.proxy_pass).to be_nil end it "configures the proxy user and pass when using https scheme" do @url.scheme = "https" http_client = new_request.http_client - http_client.proxy?.should == true - http_client.proxy_user.should == "homie" - http_client.proxy_pass.should == "theclown" + expect(http_client.proxy?).to eq(true) + expect(http_client.proxy_user).to eq("homie") + expect(http_client.proxy_pass).to eq("theclown") end end end diff --git a/spec/unit/rest_spec.rb b/spec/unit/rest_spec.rb index 3047366c47..1aa7ac84ee 100644 --- a/spec/unit/rest_spec.rb +++ b/spec/unit/rest_spec.rb @@ -83,7 +83,7 @@ describe Chef::REST do expect(content_length).not_to be_nil expect(decompressor).not_to be_nil - expect(decompressor < content_length).to be_true + expect(decompressor < content_length).to be_truthy end it "should allow the options hash to be frozen" do @@ -214,7 +214,7 @@ describe Chef::REST do it "indicates that requests should not be signed when it has no credentials" do rest = Chef::REST.new(base_url, nil, nil) - expect(rest.sign_requests?).to be_false + expect(rest.sign_requests?).to be_falsey end it "raises PrivateKeyMissing when the key file doesn't exist" do @@ -462,7 +462,7 @@ describe Chef::REST do end it "should return `false`" do - expect(rest.request(:GET, url)).to be_false + expect(rest.request(:GET, url)).to be_falsey end end @@ -616,10 +616,10 @@ describe Chef::REST do tempfile_path = nil rest.streaming_request(url, {}) do |tempfile| tempfile_path = tempfile.path - expect(File.exist?(tempfile.path)).to be_true + expect(File.exist?(tempfile.path)).to be_truthy expect(IO.read(tempfile.path).chomp).to eq("realultimatepower") end - expect(File.exist?(tempfile_path)).to be_false + expect(File.exist?(tempfile_path)).to be_falsey end it "does not raise a divide by zero exception if the content's actual size is 0" do @@ -648,7 +648,7 @@ describe Chef::REST do tempfile_path = tempfile.path expect(IO.read(tempfile.path).chomp).to eq("realultimatepower") end - expect(File.exist?(tempfile_path)).to be_false + expect(File.exist?(tempfile_path)).to be_falsey end it "closes and unlinks the tempfile if there is an error while streaming the content to the tempfile" do @@ -656,7 +656,7 @@ describe Chef::REST do expect(path).not_to be_nil allow(tempfile).to receive(:write).and_raise(IOError) rest.fetch("cookbooks/a_cookbook") {|tmpfile| "shouldn't get here"} - expect(File.exists?(path)).to be_false + expect(File.exists?(path)).to be_falsey end it "closes and unlinks the tempfile when the response is a redirect" do @@ -683,7 +683,7 @@ describe Chef::REST do rest.fetch("cookbooks/a_cookbook") do |tmpfile| block_called = true end - expect(block_called).to be_true + expect(block_called).to be_truthy end end end @@ -718,15 +718,15 @@ describe Chef::REST do it "does not sign the redirected request when sign_on_redirect is false" do rest.sign_on_redirect = false - rest.follow_redirect { expect(rest.sign_requests?).to be_false } + rest.follow_redirect { expect(rest.sign_requests?).to be_falsey } end it "resets sign_requests to the original value after following an unsigned redirect" do rest.sign_on_redirect = false - expect(rest.sign_requests?).to be_true + expect(rest.sign_requests?).to be_truthy - rest.follow_redirect { expect(rest.sign_requests?).to be_false } - expect(rest.sign_requests?).to be_true + rest.follow_redirect { expect(rest.sign_requests?).to be_falsey } + expect(rest.sign_requests?).to be_truthy end it "configures the redirect limit" do diff --git a/spec/unit/role_spec.rb b/spec/unit/role_spec.rb index 1a108c4247..5421b5a7b3 100644 --- a/spec/unit/role_spec.rb +++ b/spec/unit/role_spec.rb @@ -21,21 +21,21 @@ require 'chef/role' describe Chef::Role do before(:each) do - Chef::Platform.stub(:windows?) { false } + allow(Chef::Platform).to receive(:windows?) { false } @role = Chef::Role.new @role.name("ops_master") end it "has a name" do - @role.name("ops_master").should == "ops_master" + expect(@role.name("ops_master")).to eq("ops_master") end it "does not accept a name with spaces" do - lambda { @role.name "ops master" }.should raise_error(ArgumentError) + expect { @role.name "ops master" }.to raise_error(ArgumentError) end it "does not accept non-String objects for the name" do - lambda { @role.name({}) }.should raise_error(ArgumentError) + expect { @role.name({}) }.to raise_error(ArgumentError) end describe "when a run list is set" do @@ -46,7 +46,7 @@ describe Chef::Role do it "returns the run list" do - @role.run_list.should == %w{ nginx recipe[ree] role[base]} + expect(@role.run_list).to eq(%w{ nginx recipe[ree] role[base]}) end describe "and per-environment run lists are set" do @@ -58,28 +58,28 @@ describe Chef::Role do end it "uses the default run list as *the* run_list" do - @role.run_list.should == Chef::RunList.new("recipe[nagios::client]", "recipe[tims-acl::bork]") + expect(@role.run_list).to eq(Chef::RunList.new("recipe[nagios::client]", "recipe[tims-acl::bork]")) end it "gives the default run list as the when getting the _default run list" do - @role.run_list_for("_default").should == @role.run_list + expect(@role.run_list_for("_default")).to eq(@role.run_list) end it "gives an environment specific run list" do - @role.run_list_for("prod").should == Chef::RunList.new("recipe[nagios::client]", "recipe[tims-acl::bork]", "recipe[prod-base]") + expect(@role.run_list_for("prod")).to eq(Chef::RunList.new("recipe[nagios::client]", "recipe[tims-acl::bork]", "recipe[prod-base]")) end it "gives the default run list when no run list exists for the given environment" do - @role.run_list_for("qa").should == @role.run_list + expect(@role.run_list_for("qa")).to eq(@role.run_list) end it "gives the environment specific run list even if it is empty" do - @role.run_list_for("dev").should == Chef::RunList.new + expect(@role.run_list_for("dev")).to eq(Chef::RunList.new) end it "env_run_lists can only be set with _default run list in it" do long_exception_name = Chef::Exceptions::InvalidEnvironmentRunListSpecification - lambda {@role.env_run_lists({})}.should raise_error(long_exception_name) + expect {@role.env_run_lists({})}.to raise_error(long_exception_name) end end @@ -87,17 +87,17 @@ describe Chef::Role do describe "using the old #recipes API" do it "should let you set the recipe array" do - @role.recipes([ "one", "two" ]).should == [ "one", "two" ] + expect(@role.recipes([ "one", "two" ])).to eq([ "one", "two" ]) end it "should let you return the recipe array" do @role.recipes([ "one", "two" ]) - @role.recipes.should == [ "one", "two" ] + expect(@role.recipes).to eq([ "one", "two" ]) end it "should not list roles in the recipe array" do @role.run_list([ "one", "role[two]"]) - @role.recipes.should == [ "recipe[one]", "role[two]" ] + expect(@role.recipes).to eq([ "recipe[one]", "role[two]" ]) end end @@ -108,31 +108,31 @@ describe Chef::Role do describe "default_attributes" do it "should let you set the default attributes hash explicitly" do - @role.default_attributes({ :one => 'two' }).should == { :one => 'two' } + expect(@role.default_attributes({ :one => 'two' })).to eq({ :one => 'two' }) end it "should let you return the default attributes hash" do @role.default_attributes({ :one => 'two' }) - @role.default_attributes.should == { :one => 'two' } + expect(@role.default_attributes).to eq({ :one => 'two' }) end it "should throw an ArgumentError if we aren't a kind of hash" do - lambda { @role.default_attributes(Array.new) }.should raise_error(ArgumentError) + expect { @role.default_attributes(Array.new) }.to raise_error(ArgumentError) end end describe "override_attributes" do it "should let you set the override attributes hash explicitly" do - @role.override_attributes({ :one => 'two' }).should == { :one => 'two' } + expect(@role.override_attributes({ :one => 'two' })).to eq({ :one => 'two' }) end it "should let you return the override attributes hash" do @role.override_attributes({ :one => 'two' }) - @role.override_attributes.should == { :one => 'two' } + expect(@role.override_attributes).to eq({ :one => 'two' }) end it "should throw an ArgumentError if we aren't a kind of hash" do - lambda { @role.override_attributes(Array.new) }.should raise_error(ArgumentError) + expect { @role.override_attributes(Array.new) }.to raise_error(ArgumentError) end end @@ -154,11 +154,11 @@ describe Chef::Role do it "should update all fields except for name" do @role.update_from!(@example) - @role.name.should == "mars_volta" - @role.description.should == @example.description - @role.run_list.should == @example.run_list - @role.default_attributes.should == @example.default_attributes - @role.override_attributes.should == @example.override_attributes + expect(@role.name).to eq("mars_volta") + expect(@role.description).to eq(@example.description) + expect(@role.run_list).to eq(@example.run_list) + expect(@role.default_attributes).to eq(@example.default_attributes) + expect(@role.override_attributes).to eq(@example.override_attributes) end end @@ -173,29 +173,29 @@ describe Chef::Role do end it "should serialize to a json hash" do - Chef::JSONCompat.to_json(@role).should match(/^\{.+\}$/) + expect(Chef::JSONCompat.to_json(@role)).to match(/^\{.+\}$/) end it "includes the name in the JSON output" do - @serialized_role.should =~ /"name":"mars_volta"/ + expect(@serialized_role).to match(/"name":"mars_volta"/) end it "includes its description in the JSON" do - @serialized_role.should match(/"description":"Great band!"/) + expect(@serialized_role).to match(/"description":"Great band!"/) end it "should include 'default_attributes'" do - @serialized_role.should =~ /"default_attributes":\{"el_groupo":"nuevo"\}/ + expect(@serialized_role).to match(/"default_attributes":\{"el_groupo":"nuevo"\}/) end it "should include 'override_attributes'" do - @serialized_role.should =~ /"override_attributes":\{"deloused":"in the comatorium"\}/ + expect(@serialized_role).to match(/"override_attributes":\{"deloused":"in the comatorium"\}/) end it "should include 'run_list'" do #Activesupport messes with Chef json formatting #This test should pass with and without activesupport - @serialized_role.should =~ /"run_list":\["recipe\[one\]","recipe\[two\]","role\[a\]"\]/ + expect(@serialized_role).to match(/"run_list":\["recipe\[one\]","recipe\[two\]","role\[a\]"\]/) end describe "and it has per-environment run lists" do @@ -207,12 +207,12 @@ describe Chef::Role do it "includes the per-environment run lists" do #Activesupport messes with Chef json formatting #This test should pass with and without activesupport - @serialized_role["env_run_lists"]["production"].should == ['role[monitoring]', 'role[auditing]', 'role[apache]'] - @serialized_role["env_run_lists"]["dev"].should == ["role[nginx]"] + expect(@serialized_role["env_run_lists"]["production"]).to eq(['role[monitoring]', 'role[auditing]', 'role[apache]']) + expect(@serialized_role["env_run_lists"]["dev"]).to eq(["role[nginx]"]) end it "does not include the default environment in the per-environment run lists" do - @serialized_role["env_run_lists"].should_not have_key("_default") + expect(@serialized_role["env_run_lists"]).not_to have_key("_default") end end @@ -233,7 +233,7 @@ describe Chef::Role do end it "should deserialize to a Chef::Role object" do - @deserial.should be_a_kind_of(Chef::Role) + expect(@deserial).to be_a_kind_of(Chef::Role) end %w{ @@ -244,7 +244,7 @@ describe Chef::Role do run_list }.each do |t| it "should preserves the '#{t}' attribute from the JSON object" do - @deserial.send(t.to_sym).should == @role.send(t.to_sym) + expect(@deserial.send(t.to_sym)).to eq(@role.send(t.to_sym)) end end end @@ -257,56 +257,57 @@ EOR describe "when loading from disk" do before do default_cache_path = windows? ? 'C:\chef' : '/var/chef' - Chef::Config.stub(:cache_path).and_return(default_cache_path) + allow(Chef::Config).to receive(:cache_path).and_return(default_cache_path) end it "should return a Chef::Role object from JSON" do - Dir.should_receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes", "#{Chef::Config[:role_path]}/memes/lolcat.json"]) + expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes", "#{Chef::Config[:role_path]}/memes/lolcat.json"]) file_path = File.join(Chef::Config[:role_path], 'memes/lolcat.json') - File.should_receive(:exists?).with(file_path).exactly(1).times.and_return(true) - IO.should_receive(:read).with(file_path).and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') - @role.should be_a_kind_of(Chef::Role) + expect(File).to receive(:exists?).with(file_path).exactly(1).times.and_return(true) + expect(IO).to receive(:read).with(file_path).and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') + expect(@role).to be_a_kind_of(Chef::Role) @role.class.from_disk("lolcat") end it "should return a Chef::Role object from a Ruby DSL" do - Dir.should_receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes", "#{Chef::Config[:role_path]}/memes/lolcat.rb"]) + expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes", "#{Chef::Config[:role_path]}/memes/lolcat.rb"]) rb_path = File.join(Chef::Config[:role_path], 'memes/lolcat.rb') - File.should_receive(:exists?).with(rb_path).exactly(2).times.and_return(true) - File.should_receive(:readable?).with(rb_path).exactly(1).times.and_return(true) - IO.should_receive(:read).with(rb_path).and_return(ROLE_DSL) - @role.should be_a_kind_of(Chef::Role) + expect(File).to receive(:exists?).with(rb_path).exactly(2).times.and_return(true) + expect(File).to receive(:readable?).with(rb_path).exactly(1).times.and_return(true) + expect(IO).to receive(:read).with(rb_path).and_return(ROLE_DSL) + expect(@role).to be_a_kind_of(Chef::Role) @role.class.from_disk("lolcat") end it "should prefer a Chef::Role Object from JSON over one from a Ruby DSL" do - Dir.should_receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes", "#{Chef::Config[:role_path]}/memes/lolcat.json", "#{Chef::Config[:role_path]}/memes/lolcat.rb"]) + expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes", "#{Chef::Config[:role_path]}/memes/lolcat.json", "#{Chef::Config[:role_path]}/memes/lolcat.rb"]) js_path = File.join(Chef::Config[:role_path], 'memes/lolcat.json') rb_path = File.join(Chef::Config[:role_path], 'memes/lolcat.rb') - File.should_receive(:exists?).with(js_path).exactly(1).times.and_return(true) - File.should_not_receive(:exists?).with(rb_path) - IO.should_receive(:read).with(js_path).and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') - @role.should be_a_kind_of(Chef::Role) + expect(File).to receive(:exists?).with(js_path).exactly(1).times.and_return(true) + expect(File).not_to receive(:exists?).with(rb_path) + expect(IO).to receive(:read).with(js_path).and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') + expect(@role).to be_a_kind_of(Chef::Role) @role.class.from_disk("lolcat") end it "should raise an exception if the file does not exist" do - Dir.should_receive(:glob).and_return(["#{Chef::Config[:role_path]}/meme.rb"]) - File.should_not_receive(:exists?) - lambda {@role.class.from_disk("lolcat")}.should raise_error(Chef::Exceptions::RoleNotFound) + expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/meme.rb"]) + expect(File).not_to receive(:exists?) + expect {@role.class.from_disk("lolcat")}.to raise_error(Chef::Exceptions::RoleNotFound) end it "should raise an exception if two files exist with the same name" do - Dir.should_receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes/lolcat.rb", "#{Chef::Config[:role_path]}/lolcat.rb"]) - File.should_not_receive(:exists?) - lambda {@role.class.from_disk("lolcat")}.should raise_error(Chef::Exceptions::DuplicateRole) + expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes/lolcat.rb", "#{Chef::Config[:role_path]}/lolcat.rb"]) + expect(File).not_to receive(:exists?) + expect {@role.class.from_disk("lolcat")}.to raise_error(Chef::Exceptions::DuplicateRole) end it "should not raise an exception if two files exist with a similar name" do - Dir.should_receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes/lolcat.rb", "#{Chef::Config[:role_path]}/super_lolcat.rb"]) - File.should_not_receive(:exists?) - lambda {@role.class.from_disk("lolcat")}.should_not raise_error(Chef::Exceptions::DuplicateRole) - end + expect(Dir).to receive(:glob).and_return(["#{Chef::Config[:role_path]}/memes/lolcat.rb", "#{Chef::Config[:role_path]}/super_lolcat.rb"]) + expect(File).to receive(:exists?).with("#{Chef::Config[:role_path]}/memes/lolcat.rb").and_return(true) + allow_any_instance_of(Chef::Role).to receive(:from_file).with("#{Chef::Config[:role_path]}/memes/lolcat.rb") + expect{ @role.class.from_disk("lolcat") }.not_to raise_error + end end describe "when loading from disk and role_path is an array" do @@ -316,45 +317,45 @@ EOR end it "should return a Chef::Role object from JSON" do - Dir.should_receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return(['/path1/lolcat.json']) - File.should_receive(:exists?).with('/path1/lolcat.json').exactly(1).times.and_return(true) - IO.should_receive(:read).with('/path1/lolcat.json').and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') - @role.should be_a_kind_of(Chef::Role) + expect(Dir).to receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return(['/path1/lolcat.json']) + expect(File).to receive(:exists?).with('/path1/lolcat.json').exactly(1).times.and_return(true) + expect(IO).to receive(:read).with('/path1/lolcat.json').and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') + expect(@role).to be_a_kind_of(Chef::Role) @role.class.from_disk("lolcat") end it "should return a Chef::Role object from JSON when role is in the second path" do - Dir.should_receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return([]) - Dir.should_receive(:glob).with(File.join('/path/path2', '**', '**')).exactly(1).times.and_return(['/path/path2/lolcat.json']) - File.should_receive(:exists?).with('/path/path2/lolcat.json').exactly(1).times.and_return(true) - IO.should_receive(:read).with('/path/path2/lolcat.json').and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') - @role.should be_a_kind_of(Chef::Role) + expect(Dir).to receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return([]) + expect(Dir).to receive(:glob).with(File.join('/path/path2', '**', '**')).exactly(1).times.and_return(['/path/path2/lolcat.json']) + expect(File).to receive(:exists?).with('/path/path2/lolcat.json').exactly(1).times.and_return(true) + expect(IO).to receive(:read).with('/path/path2/lolcat.json').and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') + expect(@role).to be_a_kind_of(Chef::Role) @role.class.from_disk("lolcat") end it "should return a Chef::Role object from a Ruby DSL" do - Dir.should_receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return(['/path1/lolcat.rb']) - File.should_receive(:exists?).with('/path1/lolcat.rb').exactly(2).times.and_return(true) - File.should_receive(:readable?).with('/path1/lolcat.rb').and_return(true) - IO.should_receive(:read).with('/path1/lolcat.rb').exactly(1).times.and_return(ROLE_DSL) - @role.should be_a_kind_of(Chef::Role) + expect(Dir).to receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return(['/path1/lolcat.rb']) + expect(File).to receive(:exists?).with('/path1/lolcat.rb').exactly(2).times.and_return(true) + expect(File).to receive(:readable?).with('/path1/lolcat.rb').and_return(true) + expect(IO).to receive(:read).with('/path1/lolcat.rb').exactly(1).times.and_return(ROLE_DSL) + expect(@role).to be_a_kind_of(Chef::Role) @role.class.from_disk("lolcat") end it "should return a Chef::Role object from a Ruby DSL when role is in the second path" do - Dir.should_receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return([]) - Dir.should_receive(:glob).with(File.join('/path/path2', '**', '**')).exactly(1).times.and_return(['/path/path2/lolcat.rb']) - File.should_receive(:exists?).with('/path/path2/lolcat.rb').exactly(2).times.and_return(true) - File.should_receive(:readable?).with('/path/path2/lolcat.rb').and_return(true) - IO.should_receive(:read).with('/path/path2/lolcat.rb').exactly(1).times.and_return(ROLE_DSL) - @role.should be_a_kind_of(Chef::Role) + expect(Dir).to receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return([]) + expect(Dir).to receive(:glob).with(File.join('/path/path2', '**', '**')).exactly(1).times.and_return(['/path/path2/lolcat.rb']) + expect(File).to receive(:exists?).with('/path/path2/lolcat.rb').exactly(2).times.and_return(true) + expect(File).to receive(:readable?).with('/path/path2/lolcat.rb').and_return(true) + expect(IO).to receive(:read).with('/path/path2/lolcat.rb').exactly(1).times.and_return(ROLE_DSL) + expect(@role).to be_a_kind_of(Chef::Role) @role.class.from_disk("lolcat") end it "should raise an exception if the file does not exist" do - Dir.should_receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return([]) - Dir.should_receive(:glob).with(File.join('/path/path2', '**', '**')).exactly(1).times.and_return([]) - lambda {@role.class.from_disk("lolcat")}.should raise_error(Chef::Exceptions::RoleNotFound) + expect(Dir).to receive(:glob).with(File.join('/path1', '**', '**')).exactly(1).times.and_return([]) + expect(Dir).to receive(:glob).with(File.join('/path/path2', '**', '**')).exactly(1).times.and_return([]) + expect {@role.class.from_disk("lolcat")}.to raise_error(Chef::Exceptions::RoleNotFound) end end diff --git a/spec/unit/run_context/cookbook_compiler_spec.rb b/spec/unit/run_context/cookbook_compiler_spec.rb index 5c50c3dd4b..20ec1d2ef7 100644 --- a/spec/unit/run_context/cookbook_compiler_spec.rb +++ b/spec/unit/run_context/cookbook_compiler_spec.rb @@ -62,7 +62,7 @@ describe Chef::RunContext::CookbookCompiler do node.run_list("dependency1::default") compiler.compile_attributes - node[:attr_load_order].should == ["dependency1::default", "dependency1::aa_first", "dependency1::zz_last"] + expect(node[:attr_load_order]).to eq(["dependency1::default", "dependency1::aa_first", "dependency1::zz_last"]) end it "loads dependencies before loading the depending cookbook's attributes" do @@ -73,11 +73,11 @@ describe Chef::RunContext::CookbookCompiler do compiler.compile_attributes # dependencies are stored in a hash so therefore unordered, but they should be loaded in sort order - node[:attr_load_order].should == ["dependency1::default", + expect(node[:attr_load_order]).to eq(["dependency1::default", "dependency1::aa_first", "dependency1::zz_last", "dependency2::default", - "test-with-deps::default"] + "test-with-deps::default"]) end it "does not follow infinite dependency loops" do @@ -86,7 +86,7 @@ describe Chef::RunContext::CookbookCompiler do # Circular deps should not cause infinite loops compiler.compile_attributes - node[:attr_load_order].should == ["circular-dep2::default", "circular-dep1::default", "test-with-circular-deps::default"] + expect(node[:attr_load_order]).to eq(["circular-dep2::default", "circular-dep1::default", "test-with-circular-deps::default"]) end it "loads attributes from cookbooks that don't have a default.rb attribute file" do @@ -94,7 +94,7 @@ describe Chef::RunContext::CookbookCompiler do compiler.compile_attributes - node[:attr_load_order].should == ["no-default-attr::server"] + expect(node[:attr_load_order]).to eq(["no-default-attr::server"]) end end @@ -108,7 +108,7 @@ describe Chef::RunContext::CookbookCompiler do node.run_list("test-with-deps::default", "test-with-circular-deps::default") compiler.compile_libraries - LibraryLoadOrder.load_order.should == ["dependency1", "dependency2", "test-with-deps", "circular-dep2", "circular-dep1", "test-with-circular-deps"] + expect(LibraryLoadOrder.load_order).to eq(["dependency1", "dependency2", "test-with-deps", "circular-dep2", "circular-dep1", "test-with-circular-deps"]) end end @@ -122,7 +122,7 @@ describe Chef::RunContext::CookbookCompiler do node.run_list("test-with-deps::default", "test-with-circular-deps::default") compiler.compile_lwrps - LibraryLoadOrder.load_order.should == ["dependency1-provider", + expect(LibraryLoadOrder.load_order).to eq(["dependency1-provider", "dependency1-resource", "dependency2-provider", "dependency2-resource", @@ -133,7 +133,7 @@ describe Chef::RunContext::CookbookCompiler do "circular-dep1-provider", "circular-dep1-resource", "test-with-circular-deps-provider", - "test-with-circular-deps-resource"] + "test-with-circular-deps-resource"]) end end @@ -148,12 +148,12 @@ describe Chef::RunContext::CookbookCompiler do node.run_list("test-with-deps::default", "test-with-circular-deps::default") compiler.compile_resource_definitions - LibraryLoadOrder.load_order.should == ["dependency1-definition", + expect(LibraryLoadOrder.load_order).to eq(["dependency1-definition", "dependency2-definition", "test-with-deps-definition", "circular-dep2-definition", "circular-dep1-definition", - "test-with-circular-deps-definition"] + "test-with-circular-deps-definition"]) end end @@ -166,19 +166,19 @@ describe Chef::RunContext::CookbookCompiler do it "should return an array of cookbook names as symbols without duplicates" do node.run_list("test-with-circular-deps::default", "circular-dep1::default", "circular-dep2::default") - compiler.cookbook_order.should == [:"circular-dep2", + expect(compiler.cookbook_order).to eq([:"circular-dep2", :"circular-dep1", - :"test-with-circular-deps"] + :"test-with-circular-deps"]) end it "determines if a cookbook is in the list of cookbooks reachable by dependency" do node.run_list("test-with-deps::default", "test-with-deps::server") - compiler.cookbook_order.should == [:dependency1, :dependency2, :"test-with-deps"] - compiler.unreachable_cookbook?(:dependency1).should be_false - compiler.unreachable_cookbook?(:dependency2).should be_false - compiler.unreachable_cookbook?(:'test-with-deps').should be_false - compiler.unreachable_cookbook?(:'circular-dep1').should be_true - compiler.unreachable_cookbook?(:'circular-dep2').should be_true + expect(compiler.cookbook_order).to eq([:dependency1, :dependency2, :"test-with-deps"]) + expect(compiler.unreachable_cookbook?(:dependency1)).to be_falsey + expect(compiler.unreachable_cookbook?(:dependency2)).to be_falsey + expect(compiler.unreachable_cookbook?(:'test-with-deps')).to be_falsey + expect(compiler.unreachable_cookbook?(:'circular-dep1')).to be_truthy + expect(compiler.unreachable_cookbook?(:'circular-dep2')).to be_truthy end diff --git a/spec/unit/run_context_spec.rb b/spec/unit/run_context_spec.rb index 21ece2abaa..bb251c9cf4 100644 --- a/spec/unit/run_context_spec.rb +++ b/spec/unit/run_context_spec.rb @@ -36,11 +36,11 @@ describe Chef::RunContext do end it "has a cookbook collection" do - @run_context.cookbook_collection.should == @cookbook_collection + expect(@run_context.cookbook_collection).to eq(@cookbook_collection) end it "has a node" do - @run_context.node.should == @node + expect(@run_context.node).to eq(@node) end describe "loading cookbooks for a run list" do @@ -53,45 +53,45 @@ describe Chef::RunContext do end @node.run_list << "test" << "test::one" << "test::two" - @node.should_receive(:loaded_recipe).with(:test, "default") - @node.should_receive(:loaded_recipe).with(:test, "one") - @node.should_receive(:loaded_recipe).with(:test, "two") + expect(@node).to receive(:loaded_recipe).with(:test, "default") + expect(@node).to receive(:loaded_recipe).with(:test, "one") + expect(@node).to receive(:loaded_recipe).with(:test, "two") @run_context.load(@node.run_list.expand('_default')) end it "should load all the definitions in the cookbooks for this node" do - @run_context.definitions.should have_key(:new_cat) - @run_context.definitions.should have_key(:new_badger) - @run_context.definitions.should have_key(:new_dog) + expect(@run_context.definitions).to have_key(:new_cat) + expect(@run_context.definitions).to have_key(:new_badger) + expect(@run_context.definitions).to have_key(:new_dog) end it "should load all the recipes specified for this node" do - @run_context.resource_collection[0].to_s.should == "cat[einstein]" - @run_context.resource_collection[1].to_s.should == "cat[loulou]" - @run_context.resource_collection[2].to_s.should == "cat[birthday]" - @run_context.resource_collection[3].to_s.should == "cat[peanut]" - @run_context.resource_collection[4].to_s.should == "cat[fat peanut]" + expect(@run_context.resource_collection[0].to_s).to eq("cat[einstein]") + expect(@run_context.resource_collection[1].to_s).to eq("cat[loulou]") + expect(@run_context.resource_collection[2].to_s).to eq("cat[birthday]") + expect(@run_context.resource_collection[3].to_s).to eq("cat[peanut]") + expect(@run_context.resource_collection[4].to_s).to eq("cat[fat peanut]") end it "loads all the attribute files in the cookbook collection" do - @run_context.loaded_fully_qualified_attribute?("test", "george").should be_true - @node[:george].should == "washington" + expect(@run_context.loaded_fully_qualified_attribute?("test", "george")).to be_truthy + expect(@node[:george]).to eq("washington") end it "registers attributes files as loaded so they won't be reloaded" do # This test unfortunately is pretty tightly intertwined with the # implementation of how nodes load attribute files, but is the only # convenient way to test this behavior. - @node.should_not_receive(:from_file) + expect(@node).not_to receive(:from_file) @node.include_attribute("test::george") end it "raises an error when attempting to include_recipe from a cookbook not reachable by run list or dependencies" do - @node.should_receive(:loaded_recipe).with(:ancient, "aliens") - lambda do + expect(@node).to receive(:loaded_recipe).with(:ancient, "aliens") + expect do @run_context.include_recipe("ancient::aliens") # In CHEF-5120, this becomes a Chef::Exceptions::MissingCookbookDependency error: - end.should raise_error(Chef::Exceptions::CookbookNotFound) + end.to raise_error(Chef::Exceptions::CookbookNotFound) end end @@ -112,8 +112,8 @@ describe Chef::RunContext do it "queries whether a given cookbook has a specific template" do - @run_context.should have_template_in_cookbook("openldap", "test.erb") - @run_context.should_not have_template_in_cookbook("openldap", "missing.erb") + expect(@run_context).to have_template_in_cookbook("openldap", "test.erb") + expect(@run_context).not_to have_template_in_cookbook("openldap", "missing.erb") end it "errors when querying for a template in a not-available cookbook" do @@ -123,8 +123,8 @@ describe Chef::RunContext do end it "queries whether a given cookbook has a specific cookbook_file" do - @run_context.should have_cookbook_file_in_cookbook("java", "java.response") - @run_context.should_not have_cookbook_file_in_cookbook("java", "missing.txt") + expect(@run_context).to have_cookbook_file_in_cookbook("java", "java.response") + expect(@run_context).not_to have_cookbook_file_in_cookbook("java", "missing.txt") end it "errors when querying for a cookbook_file in a not-available cookbook" do @@ -142,11 +142,11 @@ describe Chef::RunContext do it "stores and deletes the reboot request" do @run_context.request_reboot(expected) expect(@run_context.reboot_info).to eq(expected) - expect(@run_context.reboot_requested?).to be_true + expect(@run_context.reboot_requested?).to be_truthy @run_context.cancel_reboot expect(@run_context.reboot_info).to eq({}) - expect(@run_context.reboot_requested?).to be_false + expect(@run_context.reboot_requested?).to be_falsey end end end diff --git a/spec/unit/run_list/run_list_expansion_spec.rb b/spec/unit/run_list/run_list_expansion_spec.rb index 907e3d3985..927257875e 100644 --- a/spec/unit/run_list/run_list_expansion_spec.rb +++ b/spec/unit/run_list/run_list_expansion_spec.rb @@ -27,23 +27,23 @@ describe Chef::RunList::RunListExpansion do describe "before expanding the run list" do it "has an array of run list items" do - @expansion.run_list_items.should == @run_list.run_list_items + expect(@expansion.run_list_items).to eq(@run_list.run_list_items) end it "has default_attrs" do - @expansion.default_attrs.should == Mash.new + expect(@expansion.default_attrs).to eq(Mash.new) end it "has override attrs" do - @expansion.override_attrs.should == Mash.new + expect(@expansion.override_attrs).to eq(Mash.new) end it "it has an empty list of recipes" do - @expansion.should have(0).recipes + expect(@expansion.recipes.size).to eq(0) end it "has not applied its roles" do - @expansion.applied_role?('rage').should be_false + expect(@expansion.applied_role?('rage')).to be_falsey end end @@ -54,28 +54,28 @@ describe Chef::RunList::RunListExpansion do r.env_run_lists('_default' => [], "prod" => ["recipe[prod-only]"]) end @expansion = Chef::RunList::RunListExpansion.new("prod", @run_list.run_list_items) - @expansion.should_receive(:fetch_role).and_return(@rage_role) + expect(@expansion).to receive(:fetch_role).and_return(@rage_role) @expansion.expand end it "has the correct list of recipes for the given environment" do - @expansion.recipes.should == ["lobster", "prod-only", "fist"] + expect(@expansion.recipes).to eq(["lobster", "prod-only", "fist"]) end end describe "after applying a role" do before do - @expansion.stub(:fetch_role).and_return(Chef::Role.new) + allow(@expansion).to receive(:fetch_role).and_return(Chef::Role.new) @expansion.inflate_role('rage', "role[base]") end it "tracks the applied role" do - @expansion.applied_role?('rage').should be_true + expect(@expansion.applied_role?('rage')).to be_truthy end it "does not inflate the role again" do - @expansion.inflate_role('rage', "role[base]").should be_false + expect(@expansion.inflate_role('rage', "role[base]")).to be_falsey end end @@ -89,39 +89,39 @@ describe Chef::RunList::RunListExpansion do @second_role.run_list('recipe[crabrevenge]') @second_role.default_attributes({'foo' => 'boo'}) @second_role.override_attributes({'baz' => 'bux'}) - @expansion.stub(:fetch_role).and_return(@first_role, @second_role) + allow(@expansion).to receive(:fetch_role).and_return(@first_role, @second_role) @expansion.expand end it "has the ordered list of recipes" do - @expansion.recipes.should == ['lobster', 'crabrevenge', 'fist'] + expect(@expansion.recipes).to eq(['lobster', 'crabrevenge', 'fist']) end it "has the merged attributes from the roles with outer roles overridding inner" do - @expansion.default_attrs.should == {'foo' => 'bar'} - @expansion.override_attrs.should == {'baz' => 'qux'} + expect(@expansion.default_attrs).to eq({'foo' => 'bar'}) + expect(@expansion.override_attrs).to eq({'baz' => 'qux'}) end it "has the list of all roles applied" do # this is the correct order, but 1.8 hash order is not stable - @expansion.roles.should =~ ['rage', 'mollusk'] + expect(@expansion.roles).to match_array(['rage', 'mollusk']) end end describe "after expanding a run list with a non existant role" do before do - @expansion.stub(:fetch_role) { @expansion.role_not_found('crabrevenge', "role[base]") } + allow(@expansion).to receive(:fetch_role) { @expansion.role_not_found('crabrevenge', "role[base]") } @expansion.expand end it "is invalid" do - @expansion.should be_invalid - @expansion.errors?.should be_true # aliases + expect(@expansion).to be_invalid + expect(@expansion.errors?).to be_truthy # aliases end it "has a list of invalid role names" do - @expansion.errors.should include('crabrevenge') + expect(@expansion.errors).to include('crabrevenge') end end diff --git a/spec/unit/run_list/run_list_item_spec.rb b/spec/unit/run_list/run_list_item_spec.rb index 6b9de713da..16832c1b7d 100644 --- a/spec/unit/run_list/run_list_item_spec.rb +++ b/spec/unit/run_list/run_list_item_spec.rb @@ -22,16 +22,16 @@ describe Chef::RunList::RunListItem do describe "when creating from a Hash" do it "raises an exception when the hash doesn't have a :type key" do - lambda {Chef::RunList::RunListItem.new(:name => "tatft")}.should raise_error(ArgumentError) + expect {Chef::RunList::RunListItem.new(:name => "tatft")}.to raise_error(ArgumentError) end it "raises an exception when the hash doesn't have an :name key" do - lambda {Chef::RunList::RunListItem.new(:type => 'R') }.should raise_error(ArgumentError) + expect {Chef::RunList::RunListItem.new(:type => 'R') }.to raise_error(ArgumentError) end it "sets the name and type as given in the hash" do item = Chef::RunList::RunListItem.new(:type => 'fuuu', :name => 'uuuu') - item.to_s.should == 'fuuu[uuuu]' + expect(item.to_s).to eq('fuuu[uuuu]') end end @@ -39,47 +39,47 @@ describe Chef::RunList::RunListItem do describe "when creating an item from a string" do it "parses a qualified recipe" do item = Chef::RunList::RunListItem.new("recipe[rage]") - item.should be_a_recipe - item.should_not be_a_role - item.to_s.should == 'recipe[rage]' - item.name.should == 'rage' + expect(item).to be_a_recipe + expect(item).not_to be_a_role + expect(item.to_s).to eq('recipe[rage]') + expect(item.name).to eq('rage') end it "parses a qualified recipe with a version" do item = Chef::RunList::RunListItem.new("recipe[rage@0.1.0]") - item.should be_a_recipe - item.should_not be_a_role - item.to_s.should == 'recipe[rage@0.1.0]' - item.name.should == 'rage' - item.version.should == '0.1.0' + expect(item).to be_a_recipe + expect(item).not_to be_a_role + expect(item.to_s).to eq('recipe[rage@0.1.0]') + expect(item.name).to eq('rage') + expect(item.version).to eq('0.1.0') end it "parses a qualified role" do item = Chef::RunList::RunListItem.new("role[fist]") - item.should be_a_role - item.should_not be_a_recipe - item.to_s.should == 'role[fist]' - item.name.should == 'fist' + expect(item).to be_a_role + expect(item).not_to be_a_recipe + expect(item.to_s).to eq('role[fist]') + expect(item.name).to eq('fist') end it "parses an unqualified recipe" do item = Chef::RunList::RunListItem.new("lobster") - item.should be_a_recipe - item.should_not be_a_role - item.to_s.should == 'recipe[lobster]' - item.name.should == 'lobster' + expect(item).to be_a_recipe + expect(item).not_to be_a_role + expect(item.to_s).to eq('recipe[lobster]') + expect(item.name).to eq('lobster') end it "raises an exception when the string has typo on the type part" do - lambda {Chef::RunList::RunListItem.new("Recipe[lobster]") }.should raise_error(ArgumentError) + expect {Chef::RunList::RunListItem.new("Recipe[lobster]") }.to raise_error(ArgumentError) end it "raises an exception when the string has extra space between the type and the name" do - lambda {Chef::RunList::RunListItem.new("recipe [lobster]") }.should raise_error(ArgumentError) + expect {Chef::RunList::RunListItem.new("recipe [lobster]") }.to raise_error(ArgumentError) end it "raises an exception when the string does not close the bracket" do - lambda {Chef::RunList::RunListItem.new("recipe[lobster") }.should raise_error(ArgumentError) + expect {Chef::RunList::RunListItem.new("recipe[lobster") }.to raise_error(ArgumentError) end end @@ -87,31 +87,31 @@ describe Chef::RunList::RunListItem do it "is equal to another run list item that has the same name and type" do item1 = Chef::RunList::RunListItem.new('recipe[lrf]') item2 = Chef::RunList::RunListItem.new('recipe[lrf]') - item1.should == item2 + expect(item1).to eq(item2) end it "is not equal to another run list item with the same name and different type" do item1 = Chef::RunList::RunListItem.new('recipe[lrf]') item2 = Chef::RunList::RunListItem.new('role[lrf]') - item1.should_not == item2 + expect(item1).not_to eq(item2) end it "is not equal to another run list item with the same type and different name" do item1 = Chef::RunList::RunListItem.new('recipe[lrf]') item2 = Chef::RunList::RunListItem.new('recipe[lobsterragefist]') - item1.should_not == item2 + expect(item1).not_to eq(item2) end it "is not equal to another run list item with the same name and type but different version" do item1 = Chef::RunList::RunListItem.new('recipe[lrf,0.1.0]') item2 = Chef::RunList::RunListItem.new('recipe[lrf,0.2.0]') - item1.should_not == item2 + expect(item1).not_to eq(item2) end end describe "comparing to strings" do it "is equal to a string if that string matches its to_s representation" do - Chef::RunList::RunListItem.new('recipe[lrf]').should == 'recipe[lrf]' + expect(Chef::RunList::RunListItem.new('recipe[lrf]')).to eq('recipe[lrf]') end end end diff --git a/spec/unit/run_list/versioned_recipe_list_spec.rb b/spec/unit/run_list/versioned_recipe_list_spec.rb index 5cef32c32b..209ac37fc1 100644 --- a/spec/unit/run_list/versioned_recipe_list_spec.rb +++ b/spec/unit/run_list/versioned_recipe_list_spec.rb @@ -22,7 +22,7 @@ describe Chef::RunList::VersionedRecipeList do describe "initialize" do it "should create an empty array" do l = Chef::RunList::VersionedRecipeList.new - l.should == [] + expect(l).to eq([]) end end @@ -36,41 +36,41 @@ describe Chef::RunList::VersionedRecipeList do it "should append the recipe to the end of the list" do @list.add_recipe "rails" - @list.should == ["apt", "god", "apache2", "rails"] + expect(@list).to eq(["apt", "god", "apache2", "rails"]) end it "should not duplicate entries" do @list.add_recipe "apt" - @list.should == ["apt", "god", "apache2"] + expect(@list).to eq(["apt", "god", "apache2"]) end it "should allow you to specify a version" do @list.add_recipe "rails", "1.0.0" - @list.should == ["apt", "god", "apache2", "rails"] - @list.with_versions.should include({:name => "rails", :version => "1.0.0"}) + expect(@list).to eq(["apt", "god", "apache2", "rails"]) + expect(@list.with_versions).to include({:name => "rails", :version => "1.0.0"}) end it "should allow you to specify a version for a recipe that already exists" do @list.add_recipe "apt", "1.2.3" - @list.should == ["apt", "god", "apache2"] - @list.with_versions.should include({:name => "apt", :version => "1.2.3"}) + expect(@list).to eq(["apt", "god", "apache2"]) + expect(@list.with_versions).to include({:name => "apt", :version => "1.2.3"}) end it "should allow you to specify the same version of a recipe twice" do @list.add_recipe "rails", "1.0.0" @list.add_recipe "rails", "1.0.0" - @list.with_versions.should include({:name => "rails", :version => "1.0.0"}) + expect(@list.with_versions).to include({:name => "rails", :version => "1.0.0"}) end it "should allow you to spcify no version, even when a version already exists" do @list.add_recipe "rails", "1.0.0" @list.add_recipe "rails" - @list.with_versions.should include({:name => "rails", :version => "1.0.0"}) + expect(@list.with_versions).to include({:name => "rails", :version => "1.0.0"}) end it "should not allow multiple versions of the same recipe" do @list.add_recipe "rails", "1.0.0" - lambda {@list.add_recipe "rails", "0.1.0"}.should raise_error Chef::Exceptions::CookbookVersionConflict + expect {@list.add_recipe "rails", "0.1.0"}.to raise_error Chef::Exceptions::CookbookVersionConflict end end @@ -86,13 +86,13 @@ describe Chef::RunList::VersionedRecipeList do end it "should return an array of hashes with :name and :version" do - @list.with_versions.should == @recipes + expect(@list.with_versions).to eq(@recipes) end it "should retain the same order as the version-less list" do with_versions = @list.with_versions @list.each_with_index do |item, index| - with_versions[index][:name].should == item + expect(with_versions[index][:name]).to eq(item) end end end @@ -115,8 +115,8 @@ describe Chef::RunList::VersionedRecipeList do it "should return an array of hashes with :name and :version_constraint" do @list.with_version_constraints.each do |x| - x.should have_key :name - x[:version_constraint].should_not be nil + expect(x).to have_key :name + expect(x[:version_constraint]).not_to be nil end end end diff --git a/spec/unit/run_list_spec.rb b/spec/unit/run_list_spec.rb index cc7e29af0f..bf996de8c1 100644 --- a/spec/unit/run_list_spec.rb +++ b/spec/unit/run_list_spec.rb @@ -31,42 +31,42 @@ describe Chef::RunList do describe "<<" do it "should add a recipe to the run list and recipe list with the fully qualified name" do @run_list << 'recipe[needy]' - @run_list.should include('recipe[needy]') - @run_list.recipes.should include("needy") + expect(@run_list).to include('recipe[needy]') + expect(@run_list.recipes).to include("needy") end it "should add a role to the run list and role list with the fully qualified name" do @run_list << "role[woot]" - @run_list.should include('role[woot]') - @run_list.roles.should include('woot') + expect(@run_list).to include('role[woot]') + expect(@run_list.roles).to include('woot') end it "should accept recipes that are unqualified" do @run_list << "needy" - @run_list.should include('recipe[needy]') - @run_list.recipes.include?('needy').should == true + expect(@run_list).to include('recipe[needy]') + expect(@run_list.recipes.include?('needy')).to eq(true) end it "should not allow duplicates" do @run_list << "needy" @run_list << "needy" - @run_list.run_list.length.should == 1 - @run_list.recipes.length.should == 1 + expect(@run_list.run_list.length).to eq(1) + expect(@run_list.recipes.length).to eq(1) end it "should allow two versions of a recipe" do @run_list << "recipe[needy@0.2.0]" @run_list << "recipe[needy@0.1.0]" - @run_list.run_list.length.should == 2 - @run_list.recipes.length.should == 2 - @run_list.recipes.include?('needy').should == true + expect(@run_list.run_list.length).to eq(2) + expect(@run_list.recipes.length).to eq(2) + expect(@run_list.recipes.include?('needy')).to eq(true) end it "should not allow duplicate versions of a recipe" do @run_list << "recipe[needy@0.2.0]" @run_list << "recipe[needy@0.2.0]" - @run_list.run_list.length.should == 1 - @run_list.recipes.length.should == 1 + expect(@run_list.run_list.length).to eq(1) + expect(@run_list.recipes.length).to eq(1) end end @@ -75,12 +75,12 @@ describe Chef::RunList do # since full behavior is tested above. it "should add a recipe to the run_list" do @run_list.add 'recipe[needy]' - @run_list.should include('recipe[needy]') + expect(@run_list).to include('recipe[needy]') end it "should add a role to the run_list" do @run_list.add 'role[needy]' - @run_list.should include('role[needy]') + expect(@run_list).to include('role[needy]') end end @@ -89,43 +89,43 @@ describe Chef::RunList do @run_list << "foo" r = Chef::RunList.new r << "foo" - @run_list.should == r + expect(@run_list).to eq(r) end it "should believe a RunList is equal to an array named after it's members" do @run_list << "foo" @run_list << "baz" - @run_list.should == [ "foo", "baz" ] + expect(@run_list).to eq([ "foo", "baz" ]) end end describe "empty?" do it "should be emtpy if the run list has no members" do - @run_list.empty?.should == true + expect(@run_list.empty?).to eq(true) end it "should not be empty if the run list has members" do @run_list << "chromeo" - @run_list.empty?.should == false + expect(@run_list.empty?).to eq(false) end end describe "[]" do it "should let you look up a member in the run list by position" do @run_list << 'recipe[loulou]' - @run_list[0].should == 'recipe[loulou]' + expect(@run_list[0]).to eq('recipe[loulou]') end end describe "[]=" do it "should let you set a member of the run list by position" do @run_list[0] = 'recipe[loulou]' - @run_list[0].should == 'recipe[loulou]' + expect(@run_list[0]).to eq('recipe[loulou]') end it "should properly expand a member of the run list given by position" do @run_list[0] = 'loulou' - @run_list[0].should == 'recipe[loulou]' + expect(@run_list[0]).to eq('recipe[loulou]') end end @@ -135,8 +135,8 @@ describe Chef::RunList do @run_list << "bar" seen = Array.new @run_list.each { |r| seen << r } - seen.should be_include("recipe[foo]") - seen.should be_include("recipe[bar]") + expect(seen).to be_include("recipe[foo]") + expect(seen).to be_include("recipe[bar]") end end @@ -144,7 +144,7 @@ describe Chef::RunList do it "should yield each members index to your block" do to_add = [ "recipe[foo]", "recipe[bar]", "recipe[baz]" ] to_add.each { |i| @run_list << i } - @run_list.each_index { |i| @run_list[i].should == to_add[i] } + @run_list.each_index { |i| expect(@run_list[i]).to eq(to_add[i]) } end end @@ -160,8 +160,8 @@ describe Chef::RunList do @run_list << "chromeo" list = %w{camp chairs snakes clowns} @run_list.reset!(list) - list.each { |i| @run_list.should be_include(i) } - @run_list.include?("chromeo").should == false + list.each { |i| expect(@run_list).to be_include(i) } + expect(@run_list.include?("chromeo")).to eq(false) end end @@ -173,9 +173,9 @@ describe Chef::RunList do @role.default_attributes :one => :two @role.override_attributes :three => :four - Chef::Role.stub(:load).and_return(@role) + allow(Chef::Role).to receive(:load).and_return(@role) @rest = double("Chef::REST", { :get_rest => @role, :url => "/" }) - Chef::REST.stub(:new).and_return(@rest) + allow(Chef::REST).to receive(:new).and_return(@rest) @run_list << "role[stubby]" @run_list << "kitty" @@ -183,13 +183,13 @@ describe Chef::RunList do describe "from disk" do it "should load the role from disk" do - Chef::Role.should_receive(:from_disk).with("stubby") + expect(Chef::Role).to receive(:from_disk).with("stubby") @run_list.expand("_default", "disk") end it "should log a helpful error if the role is not available" do - Chef::Role.stub(:from_disk).and_raise(Chef::Exceptions::RoleNotFound) - Chef::Log.should_receive(:error).with("Role stubby (included by 'top level') is in the runlist but does not exist. Skipping expand.") + allow(Chef::Role).to receive(:from_disk).and_raise(Chef::Exceptions::RoleNotFound) + expect(Chef::Log).to receive(:error).with("Role stubby (included by 'top level') is in the runlist but does not exist. Skipping expand.") @run_list.expand("_default", "disk") end end @@ -198,11 +198,11 @@ describe Chef::RunList do it "should load the role from the chef server" do #@rest.should_receive(:get_rest).with("roles/stubby") expansion = @run_list.expand("_default", "server") - expansion.recipes.should == ['one', 'two', 'kitty'] + expect(expansion.recipes).to eq(['one', 'two', 'kitty']) end it "should default to expanding from the server" do - @rest.should_receive(:get_rest).with("roles/stubby") + expect(@rest).to receive(:get_rest).with("roles/stubby") @run_list.expand("_default") end @@ -213,7 +213,7 @@ describe Chef::RunList do it "expands the run list using the environment specific run list" do expansion = @run_list.expand("production", "server") - expansion.recipes.should == %w{one two five kitty} + expect(expansion.recipes).to eq(%w{one two five kitty}) end describe "and multiply nested roles" do @@ -233,13 +233,13 @@ describe Chef::RunList do end it "expands the run list using the specified environment for all nested roles" do - Chef::REST.stub(:new).and_return(@multiple_rest_requests) - @multiple_rest_requests.should_receive(:get_rest).with("roles/stubby").and_return(@role) - @multiple_rest_requests.should_receive(:get_rest).with("roles/prod-base").and_return(@role_prod_base) - @multiple_rest_requests.should_receive(:get_rest).with("roles/nested-deeper").and_return(@role_nested_deeper) + allow(Chef::REST).to receive(:new).and_return(@multiple_rest_requests) + expect(@multiple_rest_requests).to receive(:get_rest).with("roles/stubby").and_return(@role) + expect(@multiple_rest_requests).to receive(:get_rest).with("roles/prod-base").and_return(@role_prod_base) + expect(@multiple_rest_requests).to receive(:get_rest).with("roles/nested-deeper").and_return(@role_nested_deeper) expansion = @run_list.expand("production", "server") - expansion.recipes.should == %w{one two five prod-secret-sauce kitty} + expect(expansion.recipes).to eq(%w{one two five prod-secret-sauce kitty}) end end @@ -250,18 +250,18 @@ describe Chef::RunList do it "should return the list of expanded recipes" do expansion = @run_list.expand("_default") - expansion.recipes[0].should == "one" - expansion.recipes[1].should == "two" + expect(expansion.recipes[0]).to eq("one") + expect(expansion.recipes[1]).to eq("two") end it "should return the list of default attributes" do expansion = @run_list.expand("_default") - expansion.default_attrs[:one].should == :two + expect(expansion.default_attrs[:one]).to eq(:two) end it "should return the list of override attributes" do expansion = @run_list.expand("_default") - expansion.override_attrs[:three].should == :four + expect(expansion.override_attrs[:three]).to eq(:four) end it "should recurse into a child role" do @@ -270,12 +270,12 @@ describe Chef::RunList do dog.default_attributes :seven => :nine dog.run_list "three" @role.run_list << "role[dog]" - Chef::Role.stub(:from_disk).with("stubby").and_return(@role) - Chef::Role.stub(:from_disk).with("dog").and_return(dog) + allow(Chef::Role).to receive(:from_disk).with("stubby").and_return(@role) + allow(Chef::Role).to receive(:from_disk).with("dog").and_return(dog) expansion = @run_list.expand("_default", 'disk') - expansion.recipes[2].should == "three" - expansion.default_attrs[:seven].should == :nine + expect(expansion.recipes[2]).to eq("three") + expect(expansion.default_attrs[:seven]).to eq(:nine) end it "should not recurse infinitely" do @@ -284,13 +284,13 @@ describe Chef::RunList do dog.default_attributes :seven => :nine dog.run_list "role[dog]", "three" @role.run_list << "role[dog]" - Chef::Role.stub(:from_disk).with("stubby").and_return(@role) - Chef::Role.should_receive(:from_disk).with("dog").once.and_return(dog) + allow(Chef::Role).to receive(:from_disk).with("stubby").and_return(@role) + expect(Chef::Role).to receive(:from_disk).with("dog").once.and_return(dog) expansion = @run_list.expand("_default", 'disk') - expansion.recipes[2].should == "three" - expansion.recipes[3].should == "kitty" - expansion.default_attrs[:seven].should == :nine + expect(expansion.recipes[2]).to eq("three") + expect(expansion.recipes[3]).to eq("kitty") + expect(expansion.default_attrs[:seven]).to eq(:nine) end end @@ -300,11 +300,11 @@ describe Chef::RunList do end it "converts to an array of the string forms of its items" do - @run_list.to_a.should == ["recipe[nagios::client]", "role[production]", "recipe[apache2]"] + expect(@run_list.to_a).to eq(["recipe[nagios::client]", "role[production]", "recipe[apache2]"]) end it "converts to json by converting its array form" do - Chef::JSONCompat.to_json(@run_list).should == Chef::JSONCompat.to_json(["recipe[nagios::client]", "role[production]", "recipe[apache2]"]) + expect(Chef::JSONCompat.to_json(@run_list)).to eq(Chef::JSONCompat.to_json(["recipe[nagios::client]", "role[production]", "recipe[apache2]"])) end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do diff --git a/spec/unit/run_lock_spec.rb b/spec/unit/run_lock_spec.rb index 80140dfcce..51e6ba1b84 100644 --- a/spec/unit/run_lock_spec.rb +++ b/spec/unit/run_lock_spec.rb @@ -25,15 +25,15 @@ describe Chef::RunLock do describe "when first created" do it "locates the lockfile in the file cache path by default" do - Chef::Config.stub(:cache_path).and_return(default_cache_path) + allow(Chef::Config).to receive(:cache_path).and_return(default_cache_path) run_lock = Chef::RunLock.new(Chef::Config.lockfile) - run_lock.runlock_file.should == default_pid_location + expect(run_lock.runlock_file).to eq(default_pid_location) end it "locates the lockfile in the user-configured path when set" do Chef::Config.lockfile = "/tmp/chef-client-running.pid" run_lock = Chef::RunLock.new(Chef::Config.lockfile) - run_lock.runlock_file.should == "/tmp/chef-client-running.pid" + expect(run_lock.runlock_file).to eq("/tmp/chef-client-running.pid") end end @@ -42,20 +42,20 @@ describe Chef::RunLock do subject(:runlock) { Chef::RunLock.new(lockfile) } def stub_unblocked_run - runlock.stub(:test).and_return(true) + allow(runlock).to receive(:test).and_return(true) end def stub_blocked_run(duration) - runlock.stub(:test).and_return(false) - runlock.stub(:wait) { sleep(duration) } - runlock.stub(:runpid).and_return(666) # errors read blocking pid + allow(runlock).to receive(:test).and_return(false) + allow(runlock).to receive(:wait) { sleep(duration) } + allow(runlock).to receive(:runpid).and_return(666) # errors read blocking pid end describe "when Chef::Config[:run_lock_timeout] is not set (set to default)" do describe "and the lockfile is not locked by another client run" do it "should not wait" do stub_unblocked_run - Chef::RunLock.any_instance.should_not_receive(:wait) + expect_any_instance_of(Chef::RunLock).not_to receive(:wait) runlock.acquire end end @@ -63,7 +63,7 @@ describe Chef::RunLock do describe "and the lockfile is locked by another client run" do it "should wait for the lock to be released" do stub_blocked_run(0.001) - runlock.should_receive(:wait) + expect(runlock).to receive(:wait) runlock.acquire end end @@ -82,7 +82,7 @@ describe Chef::RunLock do describe "and the lockfile is not locked by another client run" do it "should acquire the lock" do stub_unblocked_run - runlock.should_not_receive(:wait) + expect(runlock).not_to receive(:wait) runlock.acquire end end @@ -90,7 +90,7 @@ describe Chef::RunLock do describe "and the lockfile is locked by another client run" do it "should raise Chef::Exceptions::RunLockTimeout" do stub_blocked_run(0.001) - runlock.should_not_receive(:wait) + expect(runlock).not_to receive(:wait) expect{ runlock.acquire }.to raise_error(Chef::Exceptions::RunLockTimeout) end end @@ -110,7 +110,7 @@ describe Chef::RunLock do describe "and the lockfile is not locked by another client run" do it "should acquire the lock" do stub_unblocked_run - runlock.should_not_receive(:wait) + expect(runlock).not_to receive(:wait) runlock.acquire end end @@ -119,7 +119,7 @@ describe Chef::RunLock do describe "and the lock is released before the timeout expires" do it "should acquire the lock" do stub_blocked_run(@timeout/2.0) - runlock.should_receive(:wait) + expect(runlock).to receive(:wait) expect{ runlock.acquire }.not_to raise_error end end @@ -127,7 +127,7 @@ describe Chef::RunLock do describe "and the lock is not released before the timeout expires" do it "should raise a RunLockTimeout exception" do stub_blocked_run(2.0) - runlock.should_receive(:wait) + expect(runlock).to receive(:wait) expect{ runlock.acquire }.to raise_error(Chef::Exceptions::RunLockTimeout) end end diff --git a/spec/unit/run_status_spec.rb b/spec/unit/run_status_spec.rb index 6c85364871..d658cb5a5a 100644 --- a/spec/unit/run_status_spec.rb +++ b/spec/unit/run_status_spec.rb @@ -39,43 +39,43 @@ describe Chef::RunStatus do end it "has a run context" do - @run_status.run_context.should equal(@run_context) + expect(@run_status.run_context).to equal(@run_context) end it "provides access to the run context's node" do - @run_status.node.should equal(@node) + expect(@run_status.node).to equal(@node) end it "converts to a hash" do - @run_status.to_hash[:node].should equal(@node) - @run_status.to_hash[:success].should be_true + expect(@run_status.to_hash[:node]).to equal(@node) + expect(@run_status.to_hash[:success]).to be_truthy end describe "after it has recorded timing information" do before do @start_time = Time.new @end_time = @start_time + 23 - Time.stub(:now).and_return(@start_time, @end_time) + allow(Time).to receive(:now).and_return(@start_time, @end_time) @run_status.start_clock @run_status.stop_clock end it "records the start time of the run" do - @run_status.start_time.should == @start_time + expect(@run_status.start_time).to eq(@start_time) end it "records the end time of the run" do - @run_status.end_time.should == @end_time + expect(@run_status.end_time).to eq(@end_time) end it "gives the elapsed time of the chef run" do - @run_status.elapsed_time.should == 23 + expect(@run_status.elapsed_time).to eq(23) end it "includes timing information in its hash form" do - @run_status.to_hash[:start_time].should == @start_time - @run_status.to_hash[:end_time].should == @end_time - @run_status.to_hash[:elapsed_time].should == 23 + expect(@run_status.to_hash[:start_time]).to eq(@start_time) + expect(@run_status.to_hash[:end_time]).to eq(@end_time) + expect(@run_status.to_hash[:elapsed_time]).to eq(23) end end @@ -87,16 +87,16 @@ describe Chef::RunStatus do end it "lists all resources" do - @run_status.all_resources.should == @all_resources + expect(@run_status.all_resources).to eq(@all_resources) end it "has no updated resources" do - @run_status.updated_resources.should be_empty + expect(@run_status.updated_resources).to be_empty end it "includes the list of all resources in its hash form" do - @run_status.to_hash[:all_resources].should == @all_resources - @run_status.to_hash[:updated_resources].should be_empty + expect(@run_status.to_hash[:all_resources]).to eq(@all_resources) + expect(@run_status.to_hash[:updated_resources]).to be_empty end describe "and some have been updated" do @@ -105,11 +105,11 @@ describe Chef::RunStatus do end it "lists the updated resources" do - @run_status.updated_resources.should == [@all_resources.first] + expect(@run_status.updated_resources).to eq([@all_resources.first]) end it "includes the list of updated resources in its hash form" do - @run_status.to_hash[:updated_resources].should == [@all_resources.first] + expect(@run_status.to_hash[:updated_resources]).to eq([@all_resources.first]) end end end @@ -123,22 +123,22 @@ describe Chef::RunStatus do end it "stores the exception" do - @run_status.exception.should equal(@exception) + expect(@run_status.exception).to equal(@exception) end it "stores the backtrace" do - @run_status.backtrace.should == @backtrace + expect(@run_status.backtrace).to eq(@backtrace) end it "says the run was not successful" do - @run_status.success?.should be_false - @run_status.failed?.should be_true + expect(@run_status.success?).to be_falsey + expect(@run_status.failed?).to be_truthy end it "converts to a hash including the exception information" do - @run_status.to_hash[:success].should be_false - @run_status.to_hash[:exception].should == "Exception: just testing" - @run_status.to_hash[:backtrace].should == @backtrace + expect(@run_status.to_hash[:success]).to be_falsey + expect(@run_status.to_hash[:exception]).to eq("Exception: just testing") + expect(@run_status.to_hash[:backtrace]).to eq(@backtrace) end end end diff --git a/spec/unit/scan_access_control_spec.rb b/spec/unit/scan_access_control_spec.rb index 48f820ff85..8cf681e994 100644 --- a/spec/unit/scan_access_control_spec.rb +++ b/spec/unit/scan_access_control_spec.rb @@ -39,9 +39,9 @@ describe Chef::ScanAccessControl do end it "does not set any fields on the current resource" do - @current_resource.owner.should be_nil - @current_resource.group.should be_nil - @current_resource.mode.should be_nil + expect(@current_resource.owner).to be_nil + expect(@current_resource.group).to be_nil + expect(@current_resource.mode).to be_nil end end @@ -50,9 +50,9 @@ describe Chef::ScanAccessControl do before do @stat = double("File::Stat for #{@new_resource.path}", :uid => 0, :gid => 0, :mode => 00100644) - File.should_receive(:realpath).with(@new_resource.path).and_return(@real_file) - File.should_receive(:stat).with(@real_file).and_return(@stat) - File.should_receive(:exist?).with(@new_resource.path).and_return(true) + expect(File).to receive(:realpath).with(@new_resource.path).and_return(@real_file) + expect(File).to receive(:stat).with(@real_file).and_return(@stat) + expect(File).to receive(:exist?).with(@new_resource.path).and_return(true) end describe "when new_resource does not specify mode, user or group" do @@ -62,26 +62,26 @@ describe Chef::ScanAccessControl do end it "sets the mode of the current resource to the current mode as a String" do - @current_resource.mode.should == "0644" + expect(@current_resource.mode).to eq("0644") end context "on unix", :unix_only do it "sets the group of the current resource to the current group as a String" do - @current_resource.group.should == Etc.getgrgid(0).name + expect(@current_resource.group).to eq(Etc.getgrgid(0).name) end it "sets the owner of the current resource to the current owner as a String" do - @current_resource.user.should == "root" + expect(@current_resource.user).to eq("root") end end context "on windows", :windows_only do it "sets the group of the current resource to the current group as a String" do - @current_resource.group.should == 0 + expect(@current_resource.group).to eq(0) end it "sets the owner of the current resource to the current owner as a String" do - @current_resource.user.should == 0 + expect(@current_resource.user).to eq(0) end end end @@ -93,7 +93,7 @@ describe Chef::ScanAccessControl do end it "sets the mode of the current resource to the file's current mode as a string" do - @current_resource.mode.should == "0644" + expect(@current_resource.mode).to eq("0644") end end @@ -104,7 +104,7 @@ describe Chef::ScanAccessControl do end it "sets the mode of the current resource to the current mode as a String" do - @current_resource.mode.should == "0644" + expect(@current_resource.mode).to eq("0644") end end @@ -117,7 +117,7 @@ describe Chef::ScanAccessControl do end it "sets the owner of current_resource to the UID of the current owner" do - @current_resource.user.should == 0 + expect(@current_resource.user).to eq(0) end end @@ -129,17 +129,17 @@ describe Chef::ScanAccessControl do it "sets the owner of current_resource to the username of the current owner" do @root_passwd = double("Struct::Passwd for uid 0", :name => "root") - Etc.should_receive(:getpwuid).with(0).and_return(@root_passwd) + expect(Etc).to receive(:getpwuid).with(0).and_return(@root_passwd) @scanner.set_all! - @current_resource.user.should == "root" + expect(@current_resource.user).to eq("root") end describe "and there is no passwd entry for the user" do it "sets the owner of the current_resource to the UID" do - Etc.should_receive(:getpwuid).with(0).and_raise(ArgumentError) + expect(Etc).to receive(:getpwuid).with(0).and_raise(ArgumentError) @scanner.set_all! - @current_resource.user.should == 0 + expect(@current_resource.user).to eq(0) end end end @@ -152,7 +152,7 @@ describe Chef::ScanAccessControl do end it "sets the group of the current_resource to the gid of the current owner" do - @current_resource.group.should == 0 + expect(@current_resource.group).to eq(0) end end @@ -164,17 +164,17 @@ describe Chef::ScanAccessControl do it "sets the group of the current resource to the group name" do @group_entry = double("Struct::Group for wheel", :name => "wheel") - Etc.should_receive(:getgrgid).with(0).and_return(@group_entry) + expect(Etc).to receive(:getgrgid).with(0).and_return(@group_entry) @scanner.set_all! - @current_resource.group.should == "wheel" + expect(@current_resource.group).to eq("wheel") end describe "and there is no group entry for the group" do it "sets the current_resource's group to the GID" do - Etc.should_receive(:getgrgid).with(0).and_raise(ArgumentError) + expect(Etc).to receive(:getgrgid).with(0).and_raise(ArgumentError) @scanner.set_all! - @current_resource.group.should == 0 + expect(@current_resource.group).to eq(0) end end diff --git a/spec/unit/search/query_spec.rb b/spec/unit/search/query_spec.rb index c7388a6234..d4ff9e4367 100644 --- a/spec/unit/search/query_spec.rb +++ b/spec/unit/search/query_spec.rb @@ -68,8 +68,8 @@ describe Chef::Search::Query do end before(:each) do - Chef::REST.stub(:new).and_return(rest) - rest.stub(:get_rest).and_return(response) + allow(Chef::REST).to receive(:new).and_return(rest) + allow(rest).to receive(:get_rest).and_return(response) end describe "search" do @@ -133,57 +133,57 @@ describe Chef::Search::Query do } } it "should accept a type as the first argument" do - lambda { query.search("node") }.should_not raise_error - lambda { query.search(:node) }.should_not raise_error - lambda { query.search(Hash.new) }.should raise_error(Chef::Exceptions::InvalidSearchQuery, /(Hash)/) + expect { query.search("node") }.not_to raise_error + expect { query.search(:node) }.not_to raise_error + expect { query.search(Hash.new) }.to raise_error(Chef::Exceptions::InvalidSearchQuery, /(Hash)/) end it "should query for every object of a type by default" do - rest.should_receive(:get_rest).with("search/node?q=*:*&sort=X_CHEF_id_CHEF_X%20asc&start=0&rows=1000").and_return(response) + expect(rest).to receive(:get_rest).with("search/node?q=*:*&sort=X_CHEF_id_CHEF_X%20asc&start=0&rows=1000").and_return(response) query.search(:node) end it "should allow a custom query" do - rest.should_receive(:get_rest).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=0&rows=1000").and_return(response) + expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=0&rows=1000").and_return(response) query.search(:node, "platform:rhel") end it "should let you set a sort order" do - rest.should_receive(:get_rest).with("search/node?q=platform:rhel&sort=id%20desc&start=0&rows=1000").and_return(response) + expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=id%20desc&start=0&rows=1000").and_return(response) query.search(:node, "platform:rhel", "id desc") end it "should let you set a starting object" do - rest.should_receive(:get_rest).with("search/node?q=platform:rhel&sort=id%20desc&start=2&rows=1000").and_return(response) + expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=id%20desc&start=2&rows=1000").and_return(response) query.search(:node, "platform:rhel", "id desc", 2) end it "should let you set how many rows to return" do - rest.should_receive(:get_rest).with("search/node?q=platform:rhel&sort=id%20desc&start=2&rows=40").and_return(response) + expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=id%20desc&start=2&rows=40").and_return(response) query.search(:node, "platform:rhel", "id desc", 2, 40) end it "should throw an exception if you pass to many options" do - lambda { query.search(:node, "platform:rhel", "id desc", 2, 40, "wrong") } - .should raise_error(Chef::Exceptions::InvalidSearchQuery, "Too many arguments! (4 for <= 3)") + expect { query.search(:node, "platform:rhel", "id desc", 2, 40, "wrong") } + .to raise_error(Chef::Exceptions::InvalidSearchQuery, "Too many arguments! (4 for <= 3)") end it "should return the raw rows, start, and total if no block is passed" do rows, start, total = query.search(:node) - rows.should equal(response["rows"]) - start.should equal(response["start"]) - total.should equal(response["total"]) + expect(rows).to equal(response["rows"]) + expect(start).to equal(response["start"]) + expect(total).to equal(response["total"]) end it "should call a block for each object in the response" do @call_me = double("blocky") - response["rows"].each { |r| @call_me.should_receive(:do).with(r) } + response["rows"].each { |r| expect(@call_me).to receive(:do).with(r) } query.search(:node) { |r| @call_me.do(r) } end it "should page through the responses" do @call_me = double("blocky") - response["rows"].each { |r| @call_me.should_receive(:do).with(r) } + response["rows"].each { |r| expect(@call_me).to receive(:do).with(r) } query.search(:node, "*:*", nil, 0, 1) { |r| @call_me.do(r) } end @@ -192,17 +192,17 @@ describe Chef::Search::Query do let(:filter_key) { :filter_result } before(:each) do - rest.should_receive(:post_rest).with(query_string, args[filter_key]).and_return(response) + expect(rest).to receive(:post_rest).with(query_string, args[filter_key]).and_return(response) end it "should return start" do start = query.search(:node, "platform:rhel", args)[1] - start.should == response['start'] + expect(start).to eq(response['start']) end it "should return total" do total = query.search(:node, "platform:rhel", args)[2] - total.should == response['total'] + expect(total).to eq(response['total']) end it "should return rows with the filter applied" do @@ -211,13 +211,13 @@ describe Chef::Search::Query do results.each_with_index do |result, idx| expected = response["rows"][idx] - result.should have_key("url") - result["url"].should == expected["url"] + expect(result).to have_key("url") + expect(result["url"]).to eq(expected["url"]) - result.should have_key("data") + expect(result).to have_key("data") filter_hash.keys.each do |filter_key| - result["data"].should have_key(filter_key) - result["data"][filter_key].should == expected["data"][filter_key] + expect(result["data"]).to have_key(filter_key) + expect(result["data"][filter_key]).to eq(expected["data"][filter_key]) end end end @@ -232,21 +232,21 @@ describe Chef::Search::Query do it "should emit a deprecation warning" do # partial_search calls search, so we'll stub search to return empty - query.stub(:search).and_return( [ [], 0, 0 ] ) - Chef::Log.should_receive(:warn).with("DEPRECATED: The 'partial_search' api is deprecated, please use the search api with 'filter_result'") + allow(query).to receive(:search).and_return( [ [], 0, 0 ] ) + expect(Chef::Log).to receive(:warn).with("DEPRECATED: The 'partial_search' api is deprecated, please use the search api with 'filter_result'") query.partial_search(:node, "platform:rhel", args) end it "should return an array of filtered hashes" do - rest.should_receive(:post_rest).with(query_string, args[filter_key]).and_return(response) + expect(rest).to receive(:post_rest).with(query_string, args[filter_key]).and_return(response) results = query.partial_search(:node, "platform:rhel", args) results.each_with_index do |result, idx| expected = response["rows"][idx] filter_hash.keys.each do |filter_key| - result.should have_key(filter_key) - result[filter_key].should == expected["data"][filter_key] + expect(result).to have_key(filter_key) + expect(result[filter_key]).to eq(expected["data"][filter_key]) end end end diff --git a/spec/unit/shell/model_wrapper_spec.rb b/spec/unit/shell/model_wrapper_spec.rb index eae3b2b581..d6da2dcffc 100644 --- a/spec/unit/shell/model_wrapper_spec.rb +++ b/spec/unit/shell/model_wrapper_spec.rb @@ -32,12 +32,12 @@ describe Shell::ModelWrapper do end it "uses the explicit model symbol" do - @wrapper.model_symbol.should == :client + expect(@wrapper.model_symbol).to eq(:client) end end it "determines the model symbol from the class name" do - @wrapper.model_symbol.should == :node + expect(@wrapper.model_symbol).to eq(:node) end describe "when listing objects" do @@ -48,16 +48,16 @@ describe Shell::ModelWrapper do @node_2.name("yummy") @server_response = {:node_1 => @node_1, :node_2 => @node_2} @wrapper = Shell::ModelWrapper.new(Chef::Node) - Chef::Node.stub(:list).and_return(@server_response) + allow(Chef::Node).to receive(:list).and_return(@server_response) end it "lists fully inflated objects without the resource IDs" do - @wrapper.all.should have(2).nodes - @wrapper.all.should include(@node_1, @node_2) + expect(@wrapper.all.size).to eq(2) + expect(@wrapper.all).to include(@node_1, @node_2) end it "maps the listed nodes when given a block" do - @wrapper.all {|n| n.name }.sort.reverse.should == %w{yummy sammich} + expect(@wrapper.all {|n| n.name }.sort.reverse).to eq(%w{yummy sammich}) end end @@ -72,23 +72,23 @@ describe Shell::ModelWrapper do # Creating a Chef::Search::Query object tries to read the private key... @searcher = double("Chef::Search::Query #{__FILE__}:#{__LINE__}") - Chef::Search::Query.stub(:new).and_return(@searcher) + allow(Chef::Search::Query).to receive(:new).and_return(@searcher) end it "falls back to listing the objects when the 'query' is :all" do - Chef::Node.stub(:list).and_return(@server_response) - @wrapper.find(:all).should include(@node_1, @node_2) + allow(Chef::Node).to receive(:list).and_return(@server_response) + expect(@wrapper.find(:all)).to include(@node_1, @node_2) end it "searches for objects using the given query string" do - @searcher.should_receive(:search).with(:node, 'name:app*').and_yield(@node_1).and_yield(@node_2) - @wrapper.find("name:app*").should include(@node_1, @node_2) + expect(@searcher).to receive(:search).with(:node, 'name:app*').and_yield(@node_1).and_yield(@node_2) + expect(@wrapper.find("name:app*")).to include(@node_1, @node_2) end it "creates a 'AND'-joined query string from a HASH" do # Hash order woes - @searcher.should_receive(:search).with(:node, 'name:app* AND name:app*').and_yield(@node_1).and_yield(@node_2) - @wrapper.find(:name=>"app*",'name'=>"app*").should include(@node_1, @node_2) + expect(@searcher).to receive(:search).with(:node, 'name:app* AND name:app*').and_yield(@node_1).and_yield(@node_2) + expect(@wrapper.find(:name=>"app*",'name'=>"app*")).to include(@node_1, @node_2) end end diff --git a/spec/unit/shell/shell_ext_spec.rb b/spec/unit/shell/shell_ext_spec.rb index 8485b66d23..9521ae646b 100644 --- a/spec/unit/shell/shell_ext_spec.rb +++ b/spec/unit/shell/shell_ext_spec.rb @@ -23,7 +23,7 @@ describe Shell::Extensions do before do @shell_client = TestableShellSession.instance - Shell.stub(:session).and_return(@shell_client) + allow(Shell).to receive(:session).and_return(@shell_client) @job_manager = TestJobManager.new @root_context = Object.new @root_context.instance_eval(&ObjectTestHarness) @@ -37,98 +37,98 @@ describe Shell::Extensions do irb_context = double("context", :main => target_context_obj) irb_session = double("irb session", :context => irb_context) @job_manager.jobs = [[:thread, irb_session]] - @root_context.stub(:jobs).and_return(@job_manager) + allow(@root_context).to receive(:jobs).and_return(@job_manager) @root_context.ensure_session_select_defined - @root_context.jobs.select_shell_session(target_context_obj).should == irb_session - @root_context.jobs.select_shell_session(:idontexist).should be_nil + expect(@root_context.jobs.select_shell_session(target_context_obj)).to eq(irb_session) + expect(@root_context.jobs.select_shell_session(:idontexist)).to be_nil end it "finds, then switches to a session" do @job_manager.jobs = [] - @root_context.stub(:ensure_session_select_defined) - @root_context.stub(:jobs).and_return(@job_manager) - @job_manager.should_receive(:select_shell_session).and_return(:the_shell_session) - @job_manager.should_receive(:switch).with(:the_shell_session) + allow(@root_context).to receive(:ensure_session_select_defined) + allow(@root_context).to receive(:jobs).and_return(@job_manager) + expect(@job_manager).to receive(:select_shell_session).and_return(:the_shell_session) + expect(@job_manager).to receive(:switch).with(:the_shell_session) @root_context.find_or_create_session_for(:foo) end it "creates a new session if an existing one isn't found" do @job_manager.jobs = [] - @root_context.stub(:jobs).and_return(@job_manager) - @job_manager.stub(:select_shell_session).and_return(nil) - @root_context.should_receive(:irb).with(:foo) + allow(@root_context).to receive(:jobs).and_return(@job_manager) + allow(@job_manager).to receive(:select_shell_session).and_return(nil) + expect(@root_context).to receive(:irb).with(:foo) @root_context.find_or_create_session_for(:foo) end it "switches to recipe context" do - @root_context.should respond_to(:recipe_mode) + expect(@root_context).to respond_to(:recipe_mode) @shell_client.recipe = :monkeyTime - @root_context.should_receive(:find_or_create_session_for).with(:monkeyTime) + expect(@root_context).to receive(:find_or_create_session_for).with(:monkeyTime) @root_context.recipe_mode end it "switches to attribute context" do - @root_context.should respond_to(:attributes_mode) + expect(@root_context).to respond_to(:attributes_mode) @shell_client.node = "monkeyNodeTime" - @root_context.should_receive(:find_or_create_session_for).with("monkeyNodeTime") + expect(@root_context).to receive(:find_or_create_session_for).with("monkeyNodeTime") @root_context.attributes_mode end it "has a help command" do - @root_context.should respond_to(:help) + expect(@root_context).to respond_to(:help) end it "turns irb tracing on and off" do - @root_context.should respond_to(:trace) - @root_context.conf.should_receive(:use_tracer=).with(true) - @root_context.stub(:tracing?) + expect(@root_context).to respond_to(:trace) + expect(@root_context.conf).to receive(:use_tracer=).with(true) + allow(@root_context).to receive(:tracing?) @root_context.tracing :on end it "says if tracing is on or off" do - @root_context.conf.stub(:use_tracer).and_return(true) - @root_context.should_receive(:puts).with("tracing is on") + allow(@root_context.conf).to receive(:use_tracer).and_return(true) + expect(@root_context).to receive(:puts).with("tracing is on") @root_context.tracing? end it "prints node attributes" do node = double("node", :attribute => {:foo => :bar}) @shell_client.node = node - @root_context.should_receive(:pp).with({:foo => :bar}) + expect(@root_context).to receive(:pp).with({:foo => :bar}) @root_context.ohai - @root_context.should_receive(:pp).with(:bar) + expect(@root_context).to receive(:pp).with(:bar) @root_context.ohai(:foo) end it "resets the recipe and reloads ohai data" do - @shell_client.should_receive(:reset!) + expect(@shell_client).to receive(:reset!) @root_context.reset end it "turns irb echo on and off" do - @root_context.conf.should_receive(:echo=).with(true) + expect(@root_context.conf).to receive(:echo=).with(true) @root_context.echo :on end it "says if echo is on or off" do - @root_context.conf.stub(:echo).and_return(true) - @root_context.should_receive(:puts).with("echo is on") + allow(@root_context.conf).to receive(:echo).and_return(true) + expect(@root_context).to receive(:puts).with("echo is on") @root_context.echo? end it "gives access to the stepable iterator" do - Shell::StandAloneSession.instance.stub(:reset!) - Shell.session.stub(:rebuild_context) + allow(Shell::StandAloneSession.instance).to receive(:reset!) + allow(Shell.session).to receive(:rebuild_context) events = Chef::EventDispatch::Dispatcher.new run_context = Chef::RunContext.new(Chef::Node.new, {}, events) run_context.resource_collection.instance_variable_get(:@resource_list).instance_variable_set(:@iterator, :the_iterator) Shell.session.run_context = run_context - @root_context.chef_run.should == :the_iterator + expect(@root_context.chef_run).to eq(:the_iterator) end it "lists directory contents" do entries = %w{. .. someFile} - Dir.should_receive(:entries).with("/tmp").and_return(entries) + expect(Dir).to receive(:entries).with("/tmp").and_return(entries) @root_context.ls "/tmp" end @@ -145,7 +145,7 @@ describe Shell::Extensions do it "gives a list of the resources" do resource = @recipe_object.file("foo") - @recipe_object.should_receive(:pp).with(["file[foo]"]) + expect(@recipe_object).to receive(:pp).with(["file[foo]"]) @recipe_object.resources end diff --git a/spec/unit/shell/shell_session_spec.rb b/spec/unit/shell/shell_session_spec.rb index f49c9fc805..d72e3fa1bb 100644 --- a/spec/unit/shell/shell_session_spec.rb +++ b/spec/unit/shell/shell_session_spec.rb @@ -42,7 +42,7 @@ end describe Shell::ShellSession do it "is a singleton object" do - Shell::ShellSession.should include(Singleton) + expect(Shell::ShellSession).to include(Singleton) end end @@ -66,13 +66,13 @@ describe Shell::ClientSession do @session.instance_variable_set(:@client, @client) @expansion = Chef::RunList::RunListExpansion.new(@node.chef_environment, []) - @node.run_list.should_receive(:expand).with(@node.chef_environment).and_return(@expansion) - Chef::REST.should_receive(:new).with(Chef::Config[:chef_server_url]).and_return(@chef_rest) + expect(@node.run_list).to receive(:expand).with(@node.chef_environment).and_return(@expansion) + expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(@chef_rest) @session.rebuild_context end it "passes the shell CLI args to the client" do - Chef::Client.should_receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) + expect(Chef::Client).to receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) @session.send(:rebuild_node) end @@ -90,30 +90,30 @@ describe Shell::StandAloneSession do end it "has a run_context" do - @session.run_context.should equal(@run_context) + expect(@session.run_context).to equal(@run_context) end it "returns a collection based on it's standalone recipe file" do - @session.resource_collection.should == @recipe.run_context.resource_collection + expect(@session.resource_collection).to eq(@recipe.run_context.resource_collection) end it "gives nil for the definitions (for now)" do - @session.definitions.should be_nil + expect(@session.definitions).to be_nil end it "gives nil for the cookbook_loader" do - @session.cookbook_loader.should be_nil + expect(@session.cookbook_loader).to be_nil end it "runs chef with the standalone recipe" do - @session.stub(:node_built?).and_return(true) - Chef::Log.stub(:level) + allow(@session).to receive(:node_built?).and_return(true) + allow(Chef::Log).to receive(:level) chef_runner = double("Chef::Runner.new", :converge => :converged) # pre-heat resource collection cache @session.resource_collection - Chef::Runner.should_receive(:new).with(@session.recipe.run_context).and_return(chef_runner) - @recipe.run_chef.should == :converged + expect(Chef::Runner).to receive(:new).with(@session.recipe.run_context).and_return(chef_runner) + expect(@recipe.run_chef).to eq(:converged) end it "passes the shell CLI args to the client" do @@ -123,7 +123,7 @@ describe Shell::StandAloneSession do :build_node => true, :register => true, :sync_cookbooks => {}) - Chef::Client.should_receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) + expect(Chef::Client).to receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) @session.send(:rebuild_node) end @@ -147,39 +147,39 @@ describe Shell::SoloSession do end it "returns a collection based on it's compilation object and the extra recipe provided by chef-shell" do - @session.stub(:node_built?).and_return(true) + allow(@session).to receive(:node_built?).and_return(true) kitteh = Chef::Resource::Cat.new("keyboard") @recipe.run_context.resource_collection << kitteh - @session.resource_collection.should include(kitteh) + expect(@session.resource_collection).to include(kitteh) end it "returns definitions from its compilation object" do - @session.definitions.should == @run_context.definitions + expect(@session.definitions).to eq(@run_context.definitions) end it "keeps json attribs and passes them to the node for consumption" do @session.node_attributes = {"besnard_lakes" => "are_the_dark_horse"} - @session.node.besnard_lakes.should == "are_the_dark_horse" + expect(@session.node.besnard_lakes).to eq("are_the_dark_horse") #pending "1) keep attribs in an ivar 2) pass them to the node 3) feed them to the node on reset" end it "generates its resource collection from the compiled cookbooks and the ad hoc recipe" do - @session.stub(:node_built?).and_return(true) + allow(@session).to receive(:node_built?).and_return(true) kitteh_cat = Chef::Resource::Cat.new("kitteh") @run_context.resource_collection << kitteh_cat keyboard_cat = Chef::Resource::Cat.new("keyboard_cat") @recipe.run_context.resource_collection << keyboard_cat #@session.rebuild_collection - @session.resource_collection.should include(kitteh_cat, keyboard_cat) + expect(@session.resource_collection).to include(kitteh_cat, keyboard_cat) end it "runs chef with a resource collection from the compiled cookbooks" do - @session.stub(:node_built?).and_return(true) - Chef::Log.stub(:level) + allow(@session).to receive(:node_built?).and_return(true) + allow(Chef::Log).to receive(:level) chef_runner = double("Chef::Runner.new", :converge => :converged) - Chef::Runner.should_receive(:new).with(an_instance_of(Chef::RunContext)).and_return(chef_runner) + expect(Chef::Runner).to receive(:new).with(an_instance_of(Chef::RunContext)).and_return(chef_runner) - @recipe.run_chef.should == :converged + expect(@recipe.run_chef).to eq(:converged) end it "passes the shell CLI args to the client" do @@ -189,7 +189,7 @@ describe Shell::SoloSession do :build_node => true, :register => true, :sync_cookbooks => {}) - Chef::Client.should_receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) + expect(Chef::Client).to receive(:new).with(nil, Chef::Config[:shell_config]).and_return(@client) @session.send(:rebuild_node) end diff --git a/spec/unit/shell_out_spec.rb b/spec/unit/shell_out_spec.rb index 1330dd16de..50b0b61cb7 100644 --- a/spec/unit/shell_out_spec.rb +++ b/spec/unit/shell_out_spec.rb @@ -2,8 +2,8 @@ require File.expand_path('../../spec_helper', __FILE__) describe "Chef::ShellOut deprecation notices" do it "logs a warning when initializing a new Chef::ShellOut object" do - Chef::Log.should_receive(:warn).with("Chef::ShellOut is deprecated, please use Mixlib::ShellOut") - Chef::Log.should_receive(:warn).with(/Called from\:/) + expect(Chef::Log).to receive(:warn).with("Chef::ShellOut is deprecated, please use Mixlib::ShellOut") + expect(Chef::Log).to receive(:warn).with(/Called from\:/) Chef::ShellOut.new("pwd") end end @@ -11,8 +11,8 @@ end describe "Chef::Exceptions::ShellCommandFailed deprecation notices" do it "logs a warning when referencing the constant Chef::Exceptions::ShellCommandFailed" do - Chef::Log.should_receive(:warn).with("Chef::Exceptions::ShellCommandFailed is deprecated, use Mixlib::ShellOut::ShellCommandFailed") - Chef::Log.should_receive(:warn).with(/Called from\:/) + expect(Chef::Log).to receive(:warn).with("Chef::Exceptions::ShellCommandFailed is deprecated, use Mixlib::ShellOut::ShellCommandFailed") + expect(Chef::Log).to receive(:warn).with(/Called from\:/) Chef::Exceptions::ShellCommandFailed end end diff --git a/spec/unit/shell_spec.rb b/spec/unit/shell_spec.rb index bf638e1c3a..58dea4c988 100644 --- a/spec/unit/shell_spec.rb +++ b/spec/unit/shell_spec.rb @@ -42,13 +42,13 @@ describe Shell do before do Shell.irb_conf = {} - Shell::ShellSession.instance.stub(:reset!) + allow(Shell::ShellSession.instance).to receive(:reset!) end describe "reporting its status" do it "alway says it is running" do - Shell.should be_running + expect(Shell).to be_running end end @@ -56,8 +56,8 @@ describe Shell do describe "configuring IRB" do it "configures irb history" do Shell.configure_irb - Shell.irb_conf[:HISTORY_FILE].should == "~/.chef/chef_shell_history" - Shell.irb_conf[:SAVE_HISTORY].should == 1000 + expect(Shell.irb_conf[:HISTORY_FILE]).to eq("~/.chef/chef_shell_history") + expect(Shell.irb_conf[:SAVE_HISTORY]).to eq(1000) end it "has a prompt like ``chef > '' in the default context" do @@ -67,12 +67,12 @@ describe Shell do conf.main = Object.new conf.main.instance_eval(&ObjectTestHarness) Shell.irb_conf[:IRB_RC].call(conf) - conf.prompt_c.should == "chef > " - conf.return_format.should == " => %s \n" - conf.prompt_i.should == "chef > " - conf.prompt_n.should == "chef ?> " - conf.prompt_s.should == "chef%l> " - conf.use_tracer.should == false + expect(conf.prompt_c).to eq("chef > ") + expect(conf.return_format).to eq(" => %s \n") + expect(conf.prompt_i).to eq("chef > ") + expect(conf.prompt_n).to eq("chef ?> ") + expect(conf.prompt_s).to eq("chef%l> ") + expect(conf.use_tracer).to eq(false) end it "has a prompt like ``chef:recipe > '' in recipe context" do @@ -82,10 +82,10 @@ describe Shell do events = Chef::EventDispatch::Dispatcher.new conf.main = Chef::Recipe.new(nil,nil,Chef::RunContext.new(Chef::Node.new, {}, events)) Shell.irb_conf[:IRB_RC].call(conf) - conf.prompt_c.should == "chef:recipe > " - conf.prompt_i.should == "chef:recipe > " - conf.prompt_n.should == "chef:recipe ?> " - conf.prompt_s.should == "chef:recipe%l> " + expect(conf.prompt_c).to eq("chef:recipe > ") + expect(conf.prompt_i).to eq("chef:recipe > ") + expect(conf.prompt_n).to eq("chef:recipe ?> ") + expect(conf.prompt_s).to eq("chef:recipe%l> ") end it "has a prompt like ``chef:attributes > '' in attributes/node context" do @@ -94,10 +94,10 @@ describe Shell do conf = OpenStruct.new conf.main = Chef::Node.new Shell.irb_conf[:IRB_RC].call(conf) - conf.prompt_c.should == "chef:attributes > " - conf.prompt_i.should == "chef:attributes > " - conf.prompt_n.should == "chef:attributes ?> " - conf.prompt_s.should == "chef:attributes%l> " + expect(conf.prompt_c).to eq("chef:attributes > ") + expect(conf.prompt_i).to eq("chef:attributes > ") + expect(conf.prompt_n).to eq("chef:attributes ?> ") + expect(conf.prompt_s).to eq("chef:attributes%l> ") end end @@ -110,7 +110,7 @@ describe Shell do end it "creates help text for methods with descriptions" do - @chef_object.help_descriptions.should == [Shell::Extensions::Help.new("rspec_method", "rspecin'", nil)] + expect(@chef_object.help_descriptions).to eq([Shell::Extensions::Help.new("rspec_method", "rspecin'", nil)]) end it "adds help text when a new method is described then defined" do @@ -120,8 +120,8 @@ describe Shell do end EVAL @chef_object.instance_eval describe_define - @chef_object.help_descriptions.should == [Shell::Extensions::Help.new("rspec_method", "rspecin'"), - Shell::Extensions::Help.new("baz", "foo2the Bar")] + expect(@chef_object.help_descriptions).to eq([Shell::Extensions::Help.new("rspec_method", "rspecin'"), + Shell::Extensions::Help.new("baz", "foo2the Bar")]) end it "adds help text for subcommands" do @@ -133,7 +133,7 @@ describe Shell do @chef_object.instance_eval describe_define expected_help_text_fragments = [Shell::Extensions::Help.new("rspec_method", "rspecin'")] expected_help_text_fragments << Shell::Extensions::Help.new("baz.baz_obj_command", "something you can do with baz.baz_obj_command") - @chef_object.help_descriptions.should == expected_help_text_fragments + expect(@chef_object.help_descriptions).to eq(expected_help_text_fragments) end it "doesn't add previous subcommand help to commands defined afterward" do @@ -147,13 +147,13 @@ describe Shell do EVAL @chef_object.instance_eval describe_define - @chef_object.help_descriptions.should have(2).descriptions - @chef_object.help_descriptions.select {|h| h.cmd == "super_monkey_time" }.should be_empty + expect(@chef_object.help_descriptions.size).to eq(2) + expect(@chef_object.help_descriptions.select {|h| h.cmd == "super_monkey_time" }).to be_empty end it "creates a help banner with the command descriptions" do - @chef_object.help_banner.should match(/^\|\ Command[\s]+\|\ Description[\s]*$/) - @chef_object.help_banner.should match(/^\|\ rspec_method[\s]+\|\ rspecin\'[\s]*$/) + expect(@chef_object.help_banner).to match(/^\|\ Command[\s]+\|\ Description[\s]*$/) + expect(@chef_object.help_banner).to match(/^\|\ rspec_method[\s]+\|\ rspecin\'[\s]*$/) end end diff --git a/spec/unit/user_spec.rb b/spec/unit/user_spec.rb index 2f2299c5bd..d451531b16 100644 --- a/spec/unit/user_spec.rb +++ b/spec/unit/user_spec.rb @@ -28,89 +28,89 @@ describe Chef::User do describe "initialize" do it "should be a Chef::User" do - @user.should be_a_kind_of(Chef::User) + expect(@user).to be_a_kind_of(Chef::User) end end describe "name" do it "should let you set the name to a string" do - @user.name("ops_master").should == "ops_master" + expect(@user.name("ops_master")).to eq("ops_master") end it "should return the current name" do @user.name "ops_master" - @user.name.should == "ops_master" + expect(@user.name).to eq("ops_master") end # It is not feasible to check all invalid characters. Here are a few # that we probably care about. it "should not accept invalid characters" do # capital letters - lambda { @user.name "Bar" }.should raise_error(ArgumentError) + expect { @user.name "Bar" }.to raise_error(ArgumentError) # slashes - lambda { @user.name "foo/bar" }.should raise_error(ArgumentError) + expect { @user.name "foo/bar" }.to raise_error(ArgumentError) # ? - lambda { @user.name "foo?" }.should raise_error(ArgumentError) + expect { @user.name "foo?" }.to raise_error(ArgumentError) # & - lambda { @user.name "foo&" }.should raise_error(ArgumentError) + expect { @user.name "foo&" }.to raise_error(ArgumentError) end it "should not accept spaces" do - lambda { @user.name "ops master" }.should raise_error(ArgumentError) + expect { @user.name "ops master" }.to raise_error(ArgumentError) end it "should throw an ArgumentError if you feed it anything but a string" do - lambda { @user.name Hash.new }.should raise_error(ArgumentError) + expect { @user.name Hash.new }.to raise_error(ArgumentError) end end describe "admin" do it "should let you set the admin bit" do - @user.admin(true).should == true + expect(@user.admin(true)).to eq(true) end it "should return the current admin value" do @user.admin true - @user.admin.should == true + expect(@user.admin).to eq(true) end it "should default to false" do - @user.admin.should == false + expect(@user.admin).to eq(false) end it "should throw an ArgumentError if you feed it anything but true or false" do - lambda { @user.name Hash.new }.should raise_error(ArgumentError) + expect { @user.name Hash.new }.to raise_error(ArgumentError) end end describe "public_key" do it "should let you set the public key" do - @user.public_key("super public").should == "super public" + expect(@user.public_key("super public")).to eq("super public") end it "should return the current public key" do @user.public_key("super public") - @user.public_key.should == "super public" + expect(@user.public_key).to eq("super public") end it "should throw an ArgumentError if you feed it something lame" do - lambda { @user.public_key Hash.new }.should raise_error(ArgumentError) + expect { @user.public_key Hash.new }.to raise_error(ArgumentError) end end describe "private_key" do it "should let you set the private key" do - @user.private_key("super private").should == "super private" + expect(@user.private_key("super private")).to eq("super private") end it "should return the private key" do @user.private_key("super private") - @user.private_key.should == "super private" + expect(@user.private_key).to eq("super private") end it "should throw an ArgumentError if you feed it something lame" do - lambda { @user.private_key Hash.new }.should raise_error(ArgumentError) + expect { @user.private_key Hash.new }.to raise_error(ArgumentError) end end @@ -122,37 +122,37 @@ describe Chef::User do end it "serializes as a JSON object" do - @json.should match(/^\{.+\}$/) + expect(@json).to match(/^\{.+\}$/) end it "includes the name value" do - @json.should include(%q{"name":"black"}) + expect(@json).to include(%q{"name":"black"}) end it "includes the public key value" do - @json.should include(%{"public_key":"crowes"}) + expect(@json).to include(%{"public_key":"crowes"}) end it "includes the 'admin' flag" do - @json.should include(%q{"admin":false}) + expect(@json).to include(%q{"admin":false}) end it "includes the private key when present" do @user.private_key("monkeypants") - @user.to_json.should include(%q{"private_key":"monkeypants"}) + expect(@user.to_json).to include(%q{"private_key":"monkeypants"}) end it "does not include the private key if not present" do - @json.should_not include("private_key") + expect(@json).not_to include("private_key") end it "includes the password if present" do @user.password "password" - @user.to_json.should include(%q{"password":"password"}) + expect(@user.to_json).to include(%q{"password":"password"}) end it "does not include the password if not present" do - @json.should_not include("password") + expect(@json).not_to include("password") end include_examples "to_json equalivent to Chef::JSONCompat.to_json" do @@ -171,27 +171,27 @@ describe Chef::User do end it "should deserialize to a Chef::User object" do - @user.should be_a_kind_of(Chef::User) + expect(@user).to be_a_kind_of(Chef::User) end it "preserves the name" do - @user.name.should == "mr_spinks" + expect(@user.name).to eq("mr_spinks") end it "preserves the public key" do - @user.public_key.should == "turtles" + expect(@user.public_key).to eq("turtles") end it "preserves the admin status" do - @user.admin.should be_true + expect(@user.admin).to be_truthy end it "includes the private key if present" do - @user.private_key.should == "pandas" + expect(@user.private_key).to eq("pandas") end it "includes the password if present" do - @user.password.should == "password" + expect(@user.password).to eq("password") end end @@ -201,7 +201,7 @@ describe Chef::User do @user = Chef::User.new @user.name "foobar" @http_client = double("Chef::REST mock") - Chef::REST.stub(:new).and_return(@http_client) + allow(Chef::REST).to receive(:new).and_return(@http_client) end describe "list" do @@ -209,61 +209,61 @@ describe Chef::User do Chef::Config[:chef_server_url] = "http://www.example.com" @osc_response = { "admin" => "http://www.example.com/users/admin"} @ohc_response = [ { "user" => { "username" => "admin" }} ] - Chef::User.stub(:load).with("admin").and_return(@user) + allow(Chef::User).to receive(:load).with("admin").and_return(@user) @osc_inflated_response = { "admin" => @user } end it "lists all clients on an OSC server" do - @http_client.stub(:get_rest).with("users").and_return(@osc_response) - Chef::User.list.should == @osc_response + allow(@http_client).to receive(:get_rest).with("users").and_return(@osc_response) + expect(Chef::User.list).to eq(@osc_response) end it "inflate all clients on an OSC server" do - @http_client.stub(:get_rest).with("users").and_return(@osc_response) - Chef::User.list(true).should == @osc_inflated_response + allow(@http_client).to receive(:get_rest).with("users").and_return(@osc_response) + expect(Chef::User.list(true)).to eq(@osc_inflated_response) end it "lists all clients on an OHC/OPC server" do - @http_client.stub(:get_rest).with("users").and_return(@ohc_response) + allow(@http_client).to receive(:get_rest).with("users").and_return(@ohc_response) # We expect that Chef::User.list will give a consistent response # so OHC API responses should be transformed to OSC-style output. - Chef::User.list.should == @osc_response + expect(Chef::User.list).to eq(@osc_response) end it "inflate all clients on an OHC/OPC server" do - @http_client.stub(:get_rest).with("users").and_return(@ohc_response) - Chef::User.list(true).should == @osc_inflated_response + allow(@http_client).to receive(:get_rest).with("users").and_return(@ohc_response) + expect(Chef::User.list(true)).to eq(@osc_inflated_response) end end describe "create" do it "creates a new user via the API" do @user.password "password" - @http_client.should_receive(:post_rest).with("users", {:name => "foobar", :admin => false, :password => "password"}).and_return({}) + expect(@http_client).to receive(:post_rest).with("users", {:name => "foobar", :admin => false, :password => "password"}).and_return({}) @user.create end end describe "read" do it "loads a named user from the API" do - @http_client.should_receive(:get_rest).with("users/foobar").and_return({"name" => "foobar", "admin" => true, "public_key" => "pubkey"}) + expect(@http_client).to receive(:get_rest).with("users/foobar").and_return({"name" => "foobar", "admin" => true, "public_key" => "pubkey"}) user = Chef::User.load("foobar") - user.name.should == "foobar" - user.admin.should == true - user.public_key.should == "pubkey" + expect(user.name).to eq("foobar") + expect(user.admin).to eq(true) + expect(user.public_key).to eq("pubkey") end end describe "update" do it "updates an existing user on via the API" do - @http_client.should_receive(:put_rest).with("users/foobar", {:name => "foobar", :admin => false}).and_return({}) + expect(@http_client).to receive(:put_rest).with("users/foobar", {:name => "foobar", :admin => false}).and_return({}) @user.update end end describe "destroy" do it "deletes the specified user via the API" do - @http_client.should_receive(:delete_rest).with("users/foobar") + expect(@http_client).to receive(:delete_rest).with("users/foobar") @user.destroy end end diff --git a/spec/unit/util/backup_spec.rb b/spec/unit/util/backup_spec.rb index 617886cede..f548e8241d 100644 --- a/spec/unit/util/backup_spec.rb +++ b/spec/unit/util/backup_spec.rb @@ -28,33 +28,33 @@ describe Chef::Util::Backup do before(:each) do @new_resource = double("new_resource") - @new_resource.should_receive(:path).at_least(:once).and_return(tempfile.path) + expect(@new_resource).to receive(:path).at_least(:once).and_return(tempfile.path) @backup = Chef::Util::Backup.new(@new_resource) end it "should store the resource passed to new as new_resource" do - @backup.new_resource.should eql(@new_resource) + expect(@backup.new_resource).to eql(@new_resource) end describe "for cases when we don't want to back anything up" do before(:each) do - @backup.should_not_receive(:do_backup) + expect(@backup).not_to receive(:do_backup) end it "should not attempt to backup a file if :backup is false" do - @new_resource.should_receive(:backup).at_least(:once).and_return(false) + expect(@new_resource).to receive(:backup).at_least(:once).and_return(false) @backup.backup! end it "should not attempt to backup a file if :backup == 0" do - @new_resource.should_receive(:backup).at_least(:once).and_return(0) + expect(@new_resource).to receive(:backup).at_least(:once).and_return(0) @backup.backup! end it "should not attempt to backup a file if it does not exist" do - @new_resource.should_receive(:backup).at_least(:once).and_return(1) - File.should_receive(:exist?).with(tempfile.path).at_least(:once).and_return(false) + expect(@new_resource).to receive(:backup).at_least(:once).and_return(1) + expect(File).to receive(:exist?).with(tempfile.path).at_least(:once).and_return(false) @backup.backup! end @@ -62,43 +62,43 @@ describe Chef::Util::Backup do describe "for cases when we want to back things up" do before(:each) do - @backup.should_receive(:do_backup) + expect(@backup).to receive(:do_backup) end describe "when the number of backups is specified as 1" do before(:each) do - @new_resource.should_receive(:backup).at_least(:once).and_return(1) + expect(@new_resource).to receive(:backup).at_least(:once).and_return(1) end it "should not delete anything if this is the only backup" do - @backup.should_receive(:sorted_backup_files).and_return(['a']) - @backup.should_not_receive(:delete_backup) + expect(@backup).to receive(:sorted_backup_files).and_return(['a']) + expect(@backup).not_to receive(:delete_backup) @backup.backup! end it "should keep only 1 backup copy" do - @backup.should_receive(:sorted_backup_files).and_return(['a', 'b', 'c']) - @backup.should_receive(:delete_backup).with('b') - @backup.should_receive(:delete_backup).with('c') + expect(@backup).to receive(:sorted_backup_files).and_return(['a', 'b', 'c']) + expect(@backup).to receive(:delete_backup).with('b') + expect(@backup).to receive(:delete_backup).with('c') @backup.backup! end end describe "when the number of backups is specified as 2" do before(:each) do - @new_resource.should_receive(:backup).at_least(:once).and_return(2) + expect(@new_resource).to receive(:backup).at_least(:once).and_return(2) end it "should not delete anything if we only have one other backup" do - @backup.should_receive(:sorted_backup_files).and_return(['a', 'b']) - @backup.should_not_receive(:delete_backup) + expect(@backup).to receive(:sorted_backup_files).and_return(['a', 'b']) + expect(@backup).not_to receive(:delete_backup) @backup.backup! end it "should keep only 2 backup copies" do - @backup.should_receive(:sorted_backup_files).and_return(['a', 'b', 'c', 'd']) - @backup.should_receive(:delete_backup).with('c') - @backup.should_receive(:delete_backup).with('d') + expect(@backup).to receive(:sorted_backup_files).and_return(['a', 'b', 'c', 'd']) + expect(@backup).to receive(:delete_backup).with('c') + expect(@backup).to receive(:delete_backup).with('d') @backup.backup! end end @@ -106,36 +106,36 @@ describe Chef::Util::Backup do describe "backup_filename" do it "should return a timestamped path" do - @backup.should_receive(:path).and_return('/a/b/c.txt') - @backup.send(:backup_filename).should =~ %r|^/a/b/c.txt.chef-\d{14}.\d{6}$| + expect(@backup).to receive(:path).and_return('/a/b/c.txt') + expect(@backup.send(:backup_filename)).to match(%r|^/a/b/c.txt.chef-\d{14}.\d{6}$|) end it "should strip the drive letter off for windows" do - @backup.should_receive(:path).and_return('c:\a\b\c.txt') - @backup.send(:backup_filename).should =~ %r|^\\a\\b\\c.txt.chef-\d{14}.\d{6}$| + expect(@backup).to receive(:path).and_return('c:\a\b\c.txt') + expect(@backup.send(:backup_filename)).to match(%r|^\\a\\b\\c.txt.chef-\d{14}.\d{6}$|) end it "should strip the drive letter off for windows (with forwardslashes)" do - @backup.should_receive(:path).and_return('c:/a/b/c.txt') - @backup.send(:backup_filename).should =~ %r|^/a/b/c.txt.chef-\d{14}.\d{6}$| + expect(@backup).to receive(:path).and_return('c:/a/b/c.txt') + expect(@backup.send(:backup_filename)).to match(%r|^/a/b/c.txt.chef-\d{14}.\d{6}$|) end end describe "backup_path" do it "uses the file's directory when Chef::Config[:file_backup_path] is nil" do - @backup.should_receive(:path).and_return('/a/b/c.txt') + expect(@backup).to receive(:path).and_return('/a/b/c.txt') Chef::Config[:file_backup_path] = nil - @backup.send(:backup_path).should =~ %r|^/a/b/c.txt.chef-\d{14}.\d{6}$| + expect(@backup.send(:backup_path)).to match(%r|^/a/b/c.txt.chef-\d{14}.\d{6}$|) end it "uses the configured Chef::Config[:file_backup_path]" do - @backup.should_receive(:path).and_return('/a/b/c.txt') + expect(@backup).to receive(:path).and_return('/a/b/c.txt') Chef::Config[:file_backup_path] = '/backupdir' - @backup.send(:backup_path).should =~ %r|^/backupdir[\\/]+a/b/c.txt.chef-\d{14}.\d{6}$| + expect(@backup.send(:backup_path)).to match(%r|^/backupdir[\\/]+a/b/c.txt.chef-\d{14}.\d{6}$|) end it "uses the configured Chef::Config[:file_backup_path] and strips the drive on windows" do - @backup.should_receive(:path).and_return('c:\\a\\b\\c.txt') + expect(@backup).to receive(:path).and_return('c:\\a\\b\\c.txt') Chef::Config[:file_backup_path] = 'c:\backupdir' - @backup.send(:backup_path).should =~ %r|^c:\\backupdir[\\/]+a\\b\\c.txt.chef-\d{14}.\d{6}$| + expect(@backup.send(:backup_path)).to match(%r|^c:\\backupdir[\\/]+a\\b\\c.txt.chef-\d{14}.\d{6}$|) end end diff --git a/spec/unit/util/diff_spec.rb b/spec/unit/util/diff_spec.rb index 947ce1d5aa..ea226f1c04 100644 --- a/spec/unit/util/diff_spec.rb +++ b/spec/unit/util/diff_spec.rb @@ -122,7 +122,7 @@ shared_examples_for "a diff util" do new_tempfile.close end it "calling for_output should return a valid diff" do - differ.for_output.join("\\n").should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_output.join("\\n")).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end it "calling for_reporting should return a utf-8 string" do expect(differ.for_reporting.encoding).to equal(Encoding::UTF_8) @@ -135,7 +135,7 @@ shared_examples_for "a diff util" do new_tempfile.close end it "calling for_output should return a valid diff" do - differ.for_output.join("\\n").should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_output.join("\\n")).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end it "calling for_reporting should return a utf-8 string" do expect(differ.for_reporting.encoding).to equal(Encoding::UTF_8) @@ -187,7 +187,7 @@ shared_examples_for "a diff util" do new_tempfile.close end it "calling for_output should return a valid diff" do - differ.for_output.join("\\n").should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_output.join("\\n")).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end it "calling for_reporting should return a utf-8 string" do expect(differ.for_reporting.encoding).to equal(Encoding::UTF_8) @@ -213,7 +213,7 @@ shared_examples_for "a diff util" do new_tempfile.close end it "calling for_output should return a valid diff" do - differ.for_output.join("\\n").should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_output.join("\\n")).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end it "calling for_reporting should return a utf-8 string" do expect(differ.for_reporting.encoding).to equal(Encoding::UTF_8) @@ -251,7 +251,7 @@ shared_examples_for "a diff util" do new_tempfile.close end it "calling for_output should return a valid diff" do - differ.for_output.join("\\n").should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_output.join("\\n")).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end it "calling for_reporting should return a utf-8 string" do expect(differ.for_reporting.encoding).to equal(Encoding::UTF_8) @@ -290,7 +290,7 @@ shared_examples_for "a diff util" do new_tempfile.close end it "calling for_output should return a valid diff" do - differ.for_output.join("\\n").should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_output.join("\\n")).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end it "calling for_reporting should return a utf-8 string" do expect(differ.for_reporting.encoding).to equal(Encoding::UTF_8) @@ -349,12 +349,12 @@ shared_examples_for "a diff util" do end it "calling for_output should return a unified diff" do - differ.for_output.size.should eql(5) - differ.for_output.join("\\n").should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_output.size).to eql(5) + expect(differ.for_output.join("\\n")).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end it "calling for_reporting should return a unified diff" do - differ.for_reporting.should match(/\A--- .*\\n\+\+\+ .*\\n@@/m) + expect(differ.for_reporting).to match(/\A--- .*\\n\+\+\+ .*\\n@@/m) end describe "when the diff output is too long" do @@ -383,7 +383,7 @@ shared_examples_for "a diff util" do it "should identify zero-length files as text" do Tempfile.open("chef-util-diff-spec") do |file| file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end @@ -391,7 +391,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(plain_ascii) file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end @@ -399,7 +399,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write("This is a binary file.\0") file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end @@ -407,7 +407,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write("This is a binary file.\nNo Really\nit is\0") file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end @@ -426,7 +426,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(plain_ascii) file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end @@ -434,7 +434,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(utf_8) file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end @@ -442,7 +442,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(latin_1) file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end @@ -450,7 +450,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(shift_jis) file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end @@ -471,7 +471,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(plain_ascii) file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end @@ -479,7 +479,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(utf_8) file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end @@ -487,7 +487,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(latin_1) file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end @@ -495,7 +495,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(shift_jis) file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end end @@ -515,14 +515,14 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(plain_ascii) file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end it "should identify UTF-8 that is invalid Shift-JIS as binary" do Tempfile.open("chef-util-diff-spec") do |file| file.write(utf_8) file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end @@ -530,7 +530,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(latin_1) file.close - differ.send(:is_binary?, file.path).should be_true + expect(differ.send(:is_binary?, file.path)).to be_truthy end end @@ -538,7 +538,7 @@ shared_examples_for "a diff util" do Tempfile.open("chef-util-diff-spec") do |file| file.write(shift_jis) file.close - differ.send(:is_binary?, file.path).should be_false + expect(differ.send(:is_binary?, file.path)).to be_falsey end end diff --git a/spec/unit/util/dsc/configuration_generator_spec.rb b/spec/unit/util/dsc/configuration_generator_spec.rb index 03f3ffe25c..c39c949991 100644 --- a/spec/unit/util/dsc/configuration_generator_spec.rb +++ b/spec/unit/util/dsc/configuration_generator_spec.rb @@ -51,9 +51,9 @@ describe Chef::Util::DSC::ConfigurationGenerator do context 'when strings are used as switches' do it 'should merge the hash if there are no restricted switches' do merged = conf_man.send(:get_merged_configuration_flags!, {'flag' => 'a'}, 'hello') - merged.should include(:flag) - merged[:flag].should eql('a') - merged.should include(:outputpath) + expect(merged).to include(:flag) + expect(merged[:flag]).to eql('a') + expect(merged).to include(:outputpath) end it 'should raise an ArgumentError if you try to override outputpath' do @@ -70,16 +70,16 @@ describe Chef::Util::DSC::ConfigurationGenerator do it 'should be case insensitive to switches that are allowed' do merged = conf_man.send(:get_merged_configuration_flags!, {'FLAG' => 'a'}, 'hello') - merged.should include(:flag) + expect(merged).to include(:flag) end end context 'when symbols are used as switches' do it 'should merge the hash if there are no restricted switches' do merged = conf_man.send(:get_merged_configuration_flags!, {:flag => 'a'}, 'hello') - merged.should include(:flag) - merged[:flag].should eql('a') - merged.should include(:outputpath) + expect(merged).to include(:flag) + expect(merged[:flag]).to eql('a') + expect(merged).to include(:outputpath) end it 'should raise an ArgumentError if you try to override outputpath' do @@ -96,21 +96,21 @@ describe Chef::Util::DSC::ConfigurationGenerator do it 'should be case insensitive to switches that are allowed' do merged = conf_man.send(:get_merged_configuration_flags!, {:FLAG => 'a'}, 'hello') - merged.should include(:flag) + expect(merged).to include(:flag) end end context 'when there are no flags' do it 'should supply an output path if configuration_flags is an empty hash' do merged = conf_man.send(:get_merged_configuration_flags!, {}, 'hello') - merged.should include(:outputpath) - merged.length.should eql(1) + expect(merged).to include(:outputpath) + expect(merged.length).to eql(1) end it 'should supply an output path if configuration_flags is an empty hash' do merged = conf_man.send(:get_merged_configuration_flags!, nil, 'hello') - merged.should include(:outputpath) - merged.length.should eql(1) + expect(merged).to include(:outputpath) + expect(merged.length).to eql(1) end end @@ -165,7 +165,7 @@ describe Chef::Util::DSC::ConfigurationGenerator do found_configuration = true end end - expect(found_configuration).to be_true + expect(found_configuration).to be_truthy end end end diff --git a/spec/unit/util/dsc/lcm_output_parser_spec.rb b/spec/unit/util/dsc/lcm_output_parser_spec.rb index 23a3dbd3ec..ba4f40c4f7 100644 --- a/spec/unit/util/dsc/lcm_output_parser_spec.rb +++ b/spec/unit/util/dsc/lcm_output_parser_spec.rb @@ -21,11 +21,11 @@ require 'chef/util/dsc/lcm_output_parser' describe Chef::Util::DSC::LocalConfigurationManager::Parser do context 'empty input parameter' do it 'returns an empty array for a 0 length string' do - Chef::Util::DSC::LocalConfigurationManager::Parser::parse('').should be_empty + expect(Chef::Util::DSC::LocalConfigurationManager::Parser::parse('')).to be_empty end it 'returns an empty array for a nil input' do - Chef::Util::DSC::LocalConfigurationManager::Parser::parse('').should be_empty + expect(Chef::Util::DSC::LocalConfigurationManager::Parser::parse('')).to be_empty end end @@ -35,7 +35,7 @@ describe Chef::Util::DSC::LocalConfigurationManager::Parser do logtype: [machinename]: LCM: [ Start Set ] logtype: [machinename]: LCM: [ End Set ] EOF - Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str).should be_empty + expect(Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str)).to be_empty end it 'returns a single resource when only 1 logged with the correct name' do @@ -46,8 +46,8 @@ logtype: [machinename]: LCM: [ End Resource ] [name] logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources.length.should eq(1) - resources[0].name.should eq('[name]') + expect(resources.length).to eq(1) + expect(resources[0].name).to eq('[name]') end it 'identifies when a resource changes the state of the system' do @@ -60,7 +60,7 @@ logtype: [machinename]: LCM: [ End Resource ] [name] logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources[0].changes_state?.should be_true + expect(resources[0].changes_state?).to be_truthy end it 'preserves the log provided for how the system changed the state' do @@ -74,7 +74,7 @@ logtype: [machinename]: LCM: [ End Resource ] [name] logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources[0].change_log.should match_array(["[name]","[message]","[name]"]) + expect(resources[0].change_log).to match_array(["[name]","[message]","[name]"]) end it 'should return false for changes_state?' do @@ -86,7 +86,7 @@ logtype: [machinename]: LCM: [ End Resource ] [name] logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources[0].changes_state?.should be_false + expect(resources[0].changes_state?).to be_falsey end it 'should return an empty array for change_log if changes_state? is false' do @@ -98,7 +98,7 @@ logtype: [machinename]: LCM: [ End Resource ] [name] logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources[0].change_log.should be_empty + expect(resources[0].change_log).to be_empty end end @@ -120,8 +120,8 @@ logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources[0].changes_state?.should be_false - resources[1].changes_state?.should be_true + expect(resources[0].changes_state?).to be_falsey + expect(resources[1].changes_state?).to be_truthy end it 'should allow missing a [End Resource] when its the first one and still find all the resource' do @@ -141,8 +141,8 @@ logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources[0].changes_state?.should be_false - resources[1].changes_state?.should be_true + expect(resources[0].changes_state?).to be_falsey + expect(resources[1].changes_state?).to be_truthy end it 'should allow missing set and end resource and assume an unconverged resource in this case' do @@ -160,10 +160,10 @@ logtype: [machinename]: LCM: [ End Resource ] logtype: [machinename]: LCM: [ End Set ] EOF resources = Chef::Util::DSC::LocalConfigurationManager::Parser::parse(str) - resources[0].changes_state?.should be_true - resources[0].name.should eql('[name]') - resources[1].changes_state?.should be_true - resources[1].name.should eql('[name2]') + expect(resources[0].changes_state?).to be_truthy + expect(resources[0].name).to eql('[name]') + expect(resources[1].changes_state?).to be_truthy + expect(resources[1].name).to eql('[name2]') end end end diff --git a/spec/unit/util/dsc/local_configuration_manager_spec.rb b/spec/unit/util/dsc/local_configuration_manager_spec.rb index eb27e9e94e..009c667c87 100644 --- a/spec/unit/util/dsc/local_configuration_manager_spec.rb +++ b/spec/unit/util/dsc/local_configuration_manager_spec.rb @@ -78,7 +78,7 @@ EOH let(:lcm_cmdlet_success) { false } it 'returns true when passed to #whatif_not_supported?' do - expect(lcm.send(:whatif_not_supported?, no_whatif_lcm_output)).to be_true + expect(lcm.send(:whatif_not_supported?, no_whatif_lcm_output)).to be_truthy end it 'should should return a (possibly empty) array of ResourceInfo instances' do diff --git a/spec/unit/util/editor_spec.rb b/spec/unit/util/editor_spec.rb index 06370f7de0..968302df17 100644 --- a/spec/unit/util/editor_spec.rb +++ b/spec/unit/util/editor_spec.rb @@ -22,7 +22,7 @@ describe Chef::Util::Editor do context 'when there is no match' do subject(:execute) { editor.append_line_after('missing', 'new') } - it('returns the number of added lines') { should be == 0 } + it('returns the number of added lines') { is_expected.to eq(0) } it 'does not add any lines' do expect { execute }.to_not change { editor.lines } end @@ -31,7 +31,7 @@ describe Chef::Util::Editor do context 'when there is a match' do subject(:execute) { editor.append_line_after('two', 'new') } - it('returns the number of added lines') { should be == 2 } + it('returns the number of added lines') { is_expected.to eq(2) } it 'adds a line after each match' do execute expect(editor.lines).to be == ['one', 'two', 'new', 'two', 'new', 'three'] @@ -48,7 +48,7 @@ describe Chef::Util::Editor do context 'when there is no match' do subject(:execute) { editor.append_line_if_missing('missing', 'new') } - it('returns the number of added lines') { should be == 1 } + it('returns the number of added lines') { is_expected.to eq(1) } it 'adds a line to the end' do execute expect(editor.lines).to be == ['one', 'two', 'two', 'three', 'new'] @@ -58,7 +58,7 @@ describe Chef::Util::Editor do context 'when there is a match' do subject(:execute) { editor.append_line_if_missing('one', 'new') } - it('returns the number of added lines') { should be == 0 } + it('returns the number of added lines') { is_expected.to eq(0) } it 'does not add any lines' do expect { execute }.to_not change { editor.lines } end @@ -74,7 +74,7 @@ describe Chef::Util::Editor do context 'when there is no match' do subject(:execute) { editor.remove_lines('missing') } - it('returns the number of removed lines') { should be == 0 } + it('returns the number of removed lines') { is_expected.to eq(0) } it 'does not remove any lines' do expect { execute }.to_not change { editor.lines } end @@ -83,7 +83,7 @@ describe Chef::Util::Editor do context 'when there is a match' do subject(:execute) { editor.remove_lines('two') } - it('returns the number of removed lines') { should be == 2 } + it('returns the number of removed lines') { is_expected.to eq(2) } it 'removes the matching lines' do execute expect(editor.lines).to be == ['one', 'three'] @@ -100,7 +100,7 @@ describe Chef::Util::Editor do context 'when there is no match' do subject(:execute) { editor.replace('missing', 'new') } - it('returns the number of changed lines') { should be == 0 } + it('returns the number of changed lines') { is_expected.to eq(0) } it 'does not change any lines' do expect { execute }.to_not change { editor.lines } end @@ -109,7 +109,7 @@ describe Chef::Util::Editor do context 'when there is a match' do subject(:execute) { editor.replace('two', 'new') } - it('returns the number of changed lines') { should be == 2 } + it('returns the number of changed lines') { is_expected.to eq(2) } it 'replaces the matching portions' do execute expect(editor.lines).to be == ['one', 'new', 'new', 'three'] @@ -127,7 +127,7 @@ describe Chef::Util::Editor do context 'when there is no match' do subject(:execute) { editor.replace_lines('missing', 'new') } - it('returns the number of changed lines') { should be == 0 } + it('returns the number of changed lines') { is_expected.to eq(0) } it 'does not change any lines' do expect { execute }.to_not change { editor.lines } end @@ -136,7 +136,7 @@ describe Chef::Util::Editor do context 'when there is a match' do subject(:execute) { editor.replace_lines('two', 'new') } - it('returns the number of replaced lines') { should be == 2 } + it('returns the number of replaced lines') { is_expected.to eq(2) } it 'replaces the matching line' do execute expect(editor.lines).to be == ['one', 'new', 'new', 'three'] diff --git a/spec/unit/util/file_edit_spec.rb b/spec/unit/util/file_edit_spec.rb index 139b29d9ce..b99cf2f426 100644 --- a/spec/unit/util/file_edit_spec.rb +++ b/spec/unit/util/file_edit_spec.rb @@ -135,21 +135,21 @@ twice describe "search_file_replace" do it "should accept regex passed in as a string (not Regexp object) and replace the match if there is one" do fedit.search_file_replace("localhost", "replacement") - fedit.unwritten_changes?.should be_true + expect(fedit.unwritten_changes?).to be_truthy fedit.write_file expect(edited_file_contents).to eq(localhost_replaced) end it "should accept regex passed in as a Regexp object and replace the match if there is one" do fedit.search_file_replace(/localhost/, "replacement") - fedit.unwritten_changes?.should be_true + expect(fedit.unwritten_changes?).to be_truthy fedit.write_file expect(edited_file_contents).to eq(localhost_replaced) end it "should do nothing if there isn't a match" do fedit.search_file_replace(/pattern/, "replacement") - fedit.unwritten_changes?.should be_false + expect(fedit.unwritten_changes?).to be_falsey fedit.write_file expect(edited_file_contents).to eq(starting_content) end @@ -158,7 +158,7 @@ twice describe "search_file_replace_line" do it "should search for match and replace the whole line" do fedit.search_file_replace_line(/localhost/, "replacement line") - fedit.unwritten_changes?.should be_true + expect(fedit.unwritten_changes?).to be_truthy fedit.write_file expect(edited_file_contents).to eq(localhost_line_replaced) end @@ -167,7 +167,7 @@ twice describe "search_file_delete" do it "should search for match and delete the match" do fedit.search_file_delete(/localhost/) - fedit.unwritten_changes?.should be_true + expect(fedit.unwritten_changes?).to be_truthy fedit.write_file expect(edited_file_contents).to eq(localhost_deleted) end @@ -176,7 +176,7 @@ twice describe "search_file_delete_line" do it "should search for match and delete the matching line" do fedit.search_file_delete_line(/localhost/) - fedit.unwritten_changes?.should be_true + expect(fedit.unwritten_changes?).to be_truthy fedit.write_file expect(edited_file_contents).to eq(localhost_line_deleted) end @@ -185,7 +185,7 @@ twice describe "insert_line_after_match" do it "should search for match and insert the given line after the matching line" do fedit.insert_line_after_match(/localhost/, "new line inserted") - fedit.unwritten_changes?.should be_true + expect(fedit.unwritten_changes?).to be_truthy fedit.write_file expect(edited_file_contents).to eq(append_after_all_localhost) end @@ -194,14 +194,14 @@ twice describe "insert_line_if_no_match" do it "should search for match and insert the given line if no line match" do fedit.insert_line_if_no_match(/pattern/, "new line inserted") - fedit.unwritten_changes?.should be_true + expect(fedit.unwritten_changes?).to be_truthy fedit.write_file expect(edited_file_contents).to eq(append_after_content) end it "should do nothing if there is a match" do fedit.insert_line_if_no_match(/localhost/, "replacement") - fedit.unwritten_changes?.should be_false + expect(fedit.unwritten_changes?).to be_falsey fedit.write_file expect(edited_file_contents).to eq(starting_content) end @@ -218,7 +218,7 @@ twice it "should return true if a file got edited" do fedit.insert_line_if_no_match(/pattern/, "new line inserted") fedit.write_file - expect(fedit.file_edited?).to be_true + expect(fedit.file_edited?).to be_truthy end end end diff --git a/spec/unit/util/path_helper_spec.rb b/spec/unit/util/path_helper_spec.rb index 1d97efc607..4df4b9b1ff 100644 --- a/spec/unit/util/path_helper_spec.rb +++ b/spec/unit/util/path_helper_spec.rb @@ -25,81 +25,81 @@ describe Chef::Util::PathHelper do [ false, true ].each do |is_windows| context "on #{is_windows ? "windows" : "unix"}" do before(:each) do - Chef::Platform.stub(:windows?).and_return(is_windows) + allow(Chef::Platform).to receive(:windows?).and_return(is_windows) end describe "join" do it "joins components when some end with separators" do expected = PathHelper.cleanpath("/foo/bar/baz") expected = "C:#{expected}" if is_windows - PathHelper.join(is_windows ? 'C:\\foo\\' : "/foo/", "bar", "baz").should == expected + expect(PathHelper.join(is_windows ? 'C:\\foo\\' : "/foo/", "bar", "baz")).to eq(expected) end it "joins components when some end and start with separators" do expected = PathHelper.cleanpath("/foo/bar/baz") expected = "C:#{expected}" if is_windows - PathHelper.join(is_windows ? 'C:\\foo\\' : "/foo/", "bar/", "/baz").should == expected + expect(PathHelper.join(is_windows ? 'C:\\foo\\' : "/foo/", "bar/", "/baz")).to eq(expected) end it "joins components that don't end in separators" do expected = PathHelper.cleanpath("/foo/bar/baz") expected = "C:#{expected}" if is_windows - PathHelper.join(is_windows ? 'C:\\foo' : "/foo", "bar", "baz").should == expected + expect(PathHelper.join(is_windows ? 'C:\\foo' : "/foo", "bar", "baz")).to eq(expected) end it "joins starting with '' resolve to absolute paths" do - PathHelper.join('', 'a', 'b').should == "#{PathHelper.path_separator}a#{PathHelper.path_separator}b" + expect(PathHelper.join('', 'a', 'b')).to eq("#{PathHelper.path_separator}a#{PathHelper.path_separator}b") end it "joins ending with '' add a / to the end" do - PathHelper.join('a', 'b', '').should == "a#{PathHelper.path_separator}b#{PathHelper.path_separator}" + expect(PathHelper.join('a', 'b', '')).to eq("a#{PathHelper.path_separator}b#{PathHelper.path_separator}") end if is_windows it "joins components on Windows when some end with unix separators" do - PathHelper.join('C:\\foo/', "bar", "baz").should == 'C:\\foo\\bar\\baz' + expect(PathHelper.join('C:\\foo/', "bar", "baz")).to eq('C:\\foo\\bar\\baz') end end end if is_windows it "path_separator is \\" do - PathHelper.path_separator.should == '\\' + expect(PathHelper.path_separator).to eq('\\') end else it "path_separator is /" do - PathHelper.path_separator.should == '/' + expect(PathHelper.path_separator).to eq('/') end end if is_windows it "cleanpath changes slashes into backslashes and leaves backslashes alone" do - PathHelper.cleanpath('/a/b\\c/d/').should == '\\a\\b\\c\\d' + expect(PathHelper.cleanpath('/a/b\\c/d/')).to eq('\\a\\b\\c\\d') end it "cleanpath does not remove leading double backslash" do - PathHelper.cleanpath('\\\\a/b\\c/d/').should == '\\\\a\\b\\c\\d' + expect(PathHelper.cleanpath('\\\\a/b\\c/d/')).to eq('\\\\a\\b\\c\\d') end else it "cleanpath removes extra slashes alone" do - PathHelper.cleanpath('/a///b/c/d/').should == '/a/b/c/d' + expect(PathHelper.cleanpath('/a///b/c/d/')).to eq('/a/b/c/d') end end describe "dirname" do it "dirname('abc') is '.'" do - PathHelper.dirname('abc').should == '.' + expect(PathHelper.dirname('abc')).to eq('.') end it "dirname('/') is '/'" do - PathHelper.dirname(PathHelper.path_separator).should == PathHelper.path_separator + expect(PathHelper.dirname(PathHelper.path_separator)).to eq(PathHelper.path_separator) end it "dirname('a/b/c') is 'a/b'" do - PathHelper.dirname(PathHelper.join('a', 'b', 'c')).should == PathHelper.join('a', 'b') + expect(PathHelper.dirname(PathHelper.join('a', 'b', 'c'))).to eq(PathHelper.join('a', 'b')) end it "dirname('a/b/c/') is 'a/b'" do - PathHelper.dirname(PathHelper.join('a', 'b', 'c', '')).should == PathHelper.join('a', 'b') + expect(PathHelper.dirname(PathHelper.join('a', 'b', 'c', ''))).to eq(PathHelper.join('a', 'b')) end it "dirname('/a/b/c') is '/a/b'" do - PathHelper.dirname(PathHelper.join('', 'a', 'b', 'c')).should == PathHelper.join('', 'a', 'b') + expect(PathHelper.dirname(PathHelper.join('', 'a', 'b', 'c'))).to eq(PathHelper.join('', 'a', 'b')) end end end @@ -109,9 +109,9 @@ describe Chef::Util::PathHelper do context "on windows" do before(:each) do # pass by default - Chef::Platform.stub(:windows?).and_return(true) - PathHelper.stub(:printable?).and_return(true) - PathHelper.stub(:windows_max_length_exceeded?).and_return(false) + allow(Chef::Platform).to receive(:windows?).and_return(true) + allow(PathHelper).to receive(:printable?).and_return(true) + allow(PathHelper).to receive(:windows_max_length_exceeded?).and_return(false) end it "returns the path if the path passes the tests" do @@ -123,14 +123,14 @@ describe Chef::Util::PathHelper do end it "raises an error if the path has invalid characters" do - PathHelper.stub(:printable?).and_return(false) + allow(PathHelper).to receive(:printable?).and_return(false) expect { PathHelper.validate_path("Newline!\n") }.to raise_error(Chef::Exceptions::ValidationFailed) end it "Adds the \\\\?\\ prefix if the path exceeds MAX_LENGTH and does not have it" do long_path = "C:\\" + "a" * 250 + "\\" + "b" * 250 prefixed_long_path = "\\\\?\\" + long_path - PathHelper.stub(:windows_max_length_exceeded?).and_return(true) + allow(PathHelper).to receive(:windows_max_length_exceeded?).and_return(true) expect(PathHelper.validate_path(long_path)).to eql(prefixed_long_path) end end @@ -138,38 +138,38 @@ describe Chef::Util::PathHelper do describe "windows_max_length_exceeded?" do it "returns true if the path is too long (259 + NUL) for the API" do - expect(PathHelper.windows_max_length_exceeded?("C:\\" + "a" * 250 + "\\" + "b" * 6)).to be_true + expect(PathHelper.windows_max_length_exceeded?("C:\\" + "a" * 250 + "\\" + "b" * 6)).to be_truthy end it "returns false if the path is not too long (259 + NUL) for the standard API" do - expect(PathHelper.windows_max_length_exceeded?("C:\\" + "a" * 250 + "\\" + "b" * 5)).to be_false + expect(PathHelper.windows_max_length_exceeded?("C:\\" + "a" * 250 + "\\" + "b" * 5)).to be_falsey end it "returns false if the path is over 259 characters but uses the \\\\?\\ prefix" do - expect(PathHelper.windows_max_length_exceeded?("\\\\?\\C:\\" + "a" * 250 + "\\" + "b" * 250)).to be_false + expect(PathHelper.windows_max_length_exceeded?("\\\\?\\C:\\" + "a" * 250 + "\\" + "b" * 250)).to be_falsey end end describe "printable?" do it "returns true if the string contains no non-printable characters" do - expect(PathHelper.printable?("C:\\Program Files (x86)\\Microsoft Office\\Files.lst")).to be_true + expect(PathHelper.printable?("C:\\Program Files (x86)\\Microsoft Office\\Files.lst")).to be_truthy end it "returns true when given 'abc' in unicode" do - expect(PathHelper.printable?("\u0061\u0062\u0063")).to be_true + expect(PathHelper.printable?("\u0061\u0062\u0063")).to be_truthy end it "returns true when given japanese unicode" do - expect(PathHelper.printable?("\uff86\uff87\uff88")).to be_true + expect(PathHelper.printable?("\uff86\uff87\uff88")).to be_truthy end it "returns false if the string contains a non-printable character" do - expect(PathHelper.printable?("\my files\work\notes.txt")).to be_false + expect(PathHelper.printable?("\my files\work\notes.txt")).to be_falsey end # This isn't necessarily a requirement, but here to be explicit about functionality. it "returns false if the string contains a newline or tab" do - expect(PathHelper.printable?("\tThere's no way,\n\t *no* way,\n\t that you came from my loins.\n")).to be_false + expect(PathHelper.printable?("\tThere's no way,\n\t *no* way,\n\t that you came from my loins.\n")).to be_falsey end end @@ -205,15 +205,15 @@ describe Chef::Util::PathHelper do describe "paths_eql?" do it "returns true if the paths are the same" do - PathHelper.stub(:canonical_path).with("bandit").and_return("c:/bandit/bandit") - PathHelper.stub(:canonical_path).with("../bandit/bandit").and_return("c:/bandit/bandit") - expect(PathHelper.paths_eql?("bandit", "../bandit/bandit")).to be_true + allow(PathHelper).to receive(:canonical_path).with("bandit").and_return("c:/bandit/bandit") + allow(PathHelper).to receive(:canonical_path).with("../bandit/bandit").and_return("c:/bandit/bandit") + expect(PathHelper.paths_eql?("bandit", "../bandit/bandit")).to be_truthy end it "returns false if the paths are different" do - PathHelper.stub(:canonical_path).with("bandit").and_return("c:/Bo/Bandit") - PathHelper.stub(:canonical_path).with("../bandit/bandit").and_return("c:/bandit/bandit") - expect(PathHelper.paths_eql?("bandit", "../bandit/bandit")).to be_false + allow(PathHelper).to receive(:canonical_path).with("bandit").and_return("c:/Bo/Bandit") + allow(PathHelper).to receive(:canonical_path).with("../bandit/bandit").and_return("c:/bandit/bandit") + expect(PathHelper.paths_eql?("bandit", "../bandit/bandit")).to be_falsey end end diff --git a/spec/unit/util/powershell/cmdlet_spec.rb b/spec/unit/util/powershell/cmdlet_spec.rb index a964f607c8..5ddf9282c4 100644 --- a/spec/unit/util/powershell/cmdlet_spec.rb +++ b/spec/unit/util/powershell/cmdlet_spec.rb @@ -51,18 +51,18 @@ describe Chef::Util::Powershell::Cmdlet do # Is this list really complete? %w{` " # '}.each do |c| it "escapse #{c}" do - @cmdlet.send(:escape_parameter_value, "stuff #{c}").should eql("stuff `#{c}") + expect(@cmdlet.send(:escape_parameter_value, "stuff #{c}")).to eql("stuff `#{c}") end end it 'does not do anything to a string without special characters' do - @cmdlet.send(:escape_parameter_value, 'stuff').should eql('stuff') + expect(@cmdlet.send(:escape_parameter_value, 'stuff')).to eql('stuff') end end describe '#escape_string_parameter_value' do it "surrounds a string with ''" do - @cmdlet.send(:escape_string_parameter_value, 'stuff').should eql("'stuff'") + expect(@cmdlet.send(:escape_string_parameter_value, 'stuff')).to eql("'stuff'") end end @@ -80,27 +80,27 @@ describe Chef::Util::Powershell::Cmdlet do end it 'ignores switches with a false value' do - @cmdlet.send(:command_switches_string, {foo: false}).should eql('') + expect(@cmdlet.send(:command_switches_string, {foo: false})).to eql('') end it 'should correctly handle a value type of string' do - @cmdlet.send(:command_switches_string, {foo: 'bar'}).should eql("-foo 'bar'") + expect(@cmdlet.send(:command_switches_string, {foo: 'bar'})).to eql("-foo 'bar'") end it 'should correctly handle a value type of string even when it is 0 length' do - @cmdlet.send(:command_switches_string, {foo: ''}).should eql("-foo ''") + expect(@cmdlet.send(:command_switches_string, {foo: ''})).to eql("-foo ''") end it 'should not quote integers' do - @cmdlet.send(:command_switches_string, {foo: 1}).should eql("-foo 1") + expect(@cmdlet.send(:command_switches_string, {foo: 1})).to eql("-foo 1") end it 'should not quote floats' do - @cmdlet.send(:command_switches_string, {foo: 1.0}).should eql("-foo 1.0") + expect(@cmdlet.send(:command_switches_string, {foo: 1.0})).to eql("-foo 1.0") end it 'has just the switch when the value is true' do - @cmdlet.send(:command_switches_string, {foo: true}).should eql("-foo") + expect(@cmdlet.send(:command_switches_string, {foo: true})).to eql("-foo") end end end diff --git a/spec/unit/util/selinux_spec.rb b/spec/unit/util/selinux_spec.rb index 53faba3db3..0ed138c7bc 100644 --- a/spec/unit/util/selinux_spec.rb +++ b/spec/unit/util/selinux_spec.rb @@ -44,17 +44,17 @@ describe Chef::Util::Selinux do expected_paths.each do |bin_path| selinux_path = File.join(bin_path, "selinuxenabled") - File.should_receive(:executable?).with(selinux_path).and_return(false) + expect(File).to receive(:executable?).with(selinux_path).and_return(false) end - @test_instance.selinux_enabled?.should be_false + expect(@test_instance.selinux_enabled?).to be_falsey end describe "when selinuxenabled binary exists" do before do @selinux_enabled_path = File.join("/sbin", "selinuxenabled") - File.stub(:executable?) do |file_path| - file_path.end_with?("selinuxenabled").should be_true + allow(File).to receive(:executable?) do |file_path| + expect(file_path.end_with?("selinuxenabled")).to be_truthy file_path == @selinux_enabled_path end end @@ -62,54 +62,54 @@ describe Chef::Util::Selinux do describe "when selinux is enabled" do before do cmd_result = double("Cmd Result", :exitstatus => 0) - @test_instance.should_receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) + expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) end it "should report selinux is enabled" do - @test_instance.selinux_enabled?.should be_true + expect(@test_instance.selinux_enabled?).to be_truthy # should check the file system only once for multiple calls - @test_instance.selinux_enabled?.should be_true + expect(@test_instance.selinux_enabled?).to be_truthy end end describe "when selinux is disabled" do before do cmd_result = double("Cmd Result", :exitstatus => 1) - @test_instance.should_receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) + expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) end it "should report selinux is disabled" do - @test_instance.selinux_enabled?.should be_false + expect(@test_instance.selinux_enabled?).to be_falsey # should check the file system only once for multiple calls - @test_instance.selinux_enabled?.should be_false + expect(@test_instance.selinux_enabled?).to be_falsey end end describe "when selinux gives an unexpected status" do before do cmd_result = double("Cmd Result", :exitstatus => 101) - @test_instance.should_receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) + expect(@test_instance).to receive(:shell_out!).once.with(@selinux_enabled_path, {:returns=>[0, 1]}).and_return(cmd_result) end it "should throw an error" do - lambda {@test_instance.selinux_enabled?}.should raise_error(RuntimeError) + expect {@test_instance.selinux_enabled?}.to raise_error(RuntimeError) end end end describe "when selinuxenabled binary doesn't exist" do before do - File.stub(:executable?) do |file_path| - file_path.end_with?("selinuxenabled").should be_true + allow(File).to receive(:executable?) do |file_path| + expect(file_path.end_with?("selinuxenabled")).to be_truthy false end end it "should report selinux is disabled" do - @test_instance.selinux_enabled?.should be_false + expect(@test_instance.selinux_enabled?).to be_falsey # should check the file system only once for multiple calls - File.should_not_receive(:executable?) - @test_instance.selinux_enabled?.should be_false + expect(File).not_to receive(:executable?) + expect(@test_instance.selinux_enabled?).to be_falsey end end @@ -118,53 +118,53 @@ describe Chef::Util::Selinux do before do @restorecon_enabled_path = File.join("/sbin", "restorecon") - File.stub(:executable?) do |file_path| - file_path.end_with?("restorecon").should be_true + allow(File).to receive(:executable?) do |file_path| + expect(file_path.end_with?("restorecon")).to be_truthy file_path == @restorecon_enabled_path end end it "should call restorecon non-recursive by default" do restorecon_command = "#{@restorecon_enabled_path} -R \"#{path}\"" - @test_instance.should_receive(:shell_out!).twice.with(restorecon_command) + expect(@test_instance).to receive(:shell_out!).twice.with(restorecon_command) @test_instance.restore_security_context(path) - File.should_not_receive(:executable?) + expect(File).not_to receive(:executable?) @test_instance.restore_security_context(path) end it "should call restorecon recursive when recursive is set" do restorecon_command = "#{@restorecon_enabled_path} -R -r \"#{path}\"" - @test_instance.should_receive(:shell_out!).twice.with(restorecon_command) + expect(@test_instance).to receive(:shell_out!).twice.with(restorecon_command) @test_instance.restore_security_context(path, true) - File.should_not_receive(:executable?) + expect(File).not_to receive(:executable?) @test_instance.restore_security_context(path, true) end it "should call restorecon non-recursive when recursive is not set" do restorecon_command = "#{@restorecon_enabled_path} -R \"#{path}\"" - @test_instance.should_receive(:shell_out!).twice.with(restorecon_command) + expect(@test_instance).to receive(:shell_out!).twice.with(restorecon_command) @test_instance.restore_security_context(path) - File.should_not_receive(:executable?) + expect(File).not_to receive(:executable?) @test_instance.restore_security_context(path) end describe "when restorecon doesn't exist on the system" do before do - File.stub(:executable?) do |file_path| - file_path.end_with?("restorecon").should be_true + allow(File).to receive(:executable?) do |file_path| + expect(file_path.end_with?("restorecon")).to be_truthy false end end it "should log a warning message" do log = [ ] - Chef::Log.stub(:warn) do |message| + allow(Chef::Log).to receive(:warn) do |message| log << message end @test_instance.restore_security_context(path) - log.should_not be_empty - File.should_not_receive(:executable?) + expect(log).not_to be_empty + expect(File).not_to receive(:executable?) @test_instance.restore_security_context(path) end end diff --git a/spec/unit/util/threaded_job_queue_spec.rb b/spec/unit/util/threaded_job_queue_spec.rb index a199937639..22626328be 100644 --- a/spec/unit/util/threaded_job_queue_spec.rb +++ b/spec/unit/util/threaded_job_queue_spec.rb @@ -23,8 +23,8 @@ describe Chef::Util::ThreadedJobQueue do it "should pass mutex to jobs with an arity of 1" do job = double() - job.should_receive(:arity).at_least(:once).and_return(1) - job.should_receive(:call).exactly(5).times.with(an_instance_of(Mutex)) + expect(job).to receive(:arity).at_least(:once).and_return(1) + expect(job).to receive(:call).exactly(5).times.with(an_instance_of(Mutex)) 5.times { queue << job } queue.process @@ -32,20 +32,20 @@ describe Chef::Util::ThreadedJobQueue do it "should pass nothing to jobs with an arity of 0" do job = double() - job.should_receive(:arity).at_least(:once).and_return(0) - job.should_receive(:call).exactly(5).times.with(no_args) + expect(job).to receive(:arity).at_least(:once).and_return(0) + expect(job).to receive(:call).exactly(5).times.with(no_args) 5.times { queue << job } queue.process end it "should use specified number of threads" do - Thread.should_receive(:new).exactly(7).times.and_call_original + expect(Thread).to receive(:new).exactly(7).times.and_call_original queue.process(7) end it "should propagate exceptions to the main thread" do queue << lambda { raise WorkerThreadError } - lambda { queue.process }.should raise_error(WorkerThreadError) + expect { queue.process }.to raise_error(WorkerThreadError) end end diff --git a/spec/unit/version/platform_spec.rb b/spec/unit/version/platform_spec.rb index 69f42e58b2..dd425b32a5 100644 --- a/spec/unit/version/platform_spec.rb +++ b/spec/unit/version/platform_spec.rb @@ -21,12 +21,12 @@ describe Chef::Version::Platform do it "is a subclass of Chef::Version" do v = Chef::Version::Platform.new('1.1') - v.should be_an_instance_of(Chef::Version::Platform) - v.should be_a_kind_of(Chef::Version) + expect(v).to be_an_instance_of(Chef::Version::Platform) + expect(v).to be_a_kind_of(Chef::Version) end it "should transform 1 to 1.0.0" do - Chef::Version::Platform.new("1").to_s.should == "1.0.0" + expect(Chef::Version::Platform.new("1").to_s).to eq("1.0.0") end describe "when creating valid Versions" do @@ -44,7 +44,7 @@ describe Chef::Version::Platform do the_error = Chef::Exceptions::InvalidPlatformVersion bad_versions.each do |v| it "should raise #{the_error} when given '#{v}'" do - lambda { Chef::Version::Platform.new v }.should raise_error(the_error) + expect { Chef::Version::Platform.new v }.to raise_error(the_error) end end end @@ -52,7 +52,7 @@ describe Chef::Version::Platform do describe "<=>" do it "should equate versions 1 and 1.0.0" do - Chef::Version::Platform.new("1").should == Chef::Version::Platform.new("1.0.0") + expect(Chef::Version::Platform.new("1")).to eq(Chef::Version::Platform.new("1.0.0")) end end diff --git a/spec/unit/version_class_spec.rb b/spec/unit/version_class_spec.rb index b0fcfbb3fb..fe1488550b 100644 --- a/spec/unit/version_class_spec.rb +++ b/spec/unit/version_class_spec.rb @@ -25,22 +25,22 @@ describe Chef::Version do end it "should turn itself into a string" do - @v0.to_s.should == "0.0.0" - @v123.to_s.should == "1.2.3" + expect(@v0.to_s).to eq("0.0.0") + expect(@v123.to_s).to eq("1.2.3") end it "should make a round trip with its string representation" do a = Chef::Version.new(@v123.to_s) - a.should == @v123 + expect(a).to eq(@v123) end it "should transform 1.2 to 1.2.0" do - Chef::Version.new("1.2").to_s.should == "1.2.0" + expect(Chef::Version.new("1.2").to_s).to eq("1.2.0") end it "should transform 01.002.0003 to 1.2.3" do a = Chef::Version.new "01.002.0003" - a.should == @v123 + expect(a).to eq(@v123) end describe "when creating valid Versions" do @@ -58,7 +58,7 @@ describe Chef::Version do the_error = Chef::Exceptions::InvalidCookbookVersion bad_versions.each do |v| it "should raise #{the_error} when given '#{v}'" do - lambda { Chef::Version.new v }.should raise_error(the_error) + expect { Chef::Version.new v }.to raise_error(the_error) end end end @@ -66,15 +66,15 @@ describe Chef::Version do describe "<=>" do it "should equate versions 1.2 and 1.2.0" do - Chef::Version.new("1.2").should == Chef::Version.new("1.2.0") + expect(Chef::Version.new("1.2")).to eq(Chef::Version.new("1.2.0")) end it "should equate version 1.04 and 1.4" do - Chef::Version.new("1.04").should == Chef::Version.new("1.4") + expect(Chef::Version.new("1.04")).to eq(Chef::Version.new("1.4")) end it "should treat versions as numbers in the right way" do - Chef::Version.new("2.0").should be < Chef::Version.new("11.0") + expect(Chef::Version.new("2.0")).to be < Chef::Version.new("11.0") end it "should sort based on the version number" do @@ -95,9 +95,9 @@ describe Chef::Version do examples.each do |smaller, larger| sm = Chef::Version.new(smaller) lg = Chef::Version.new(larger) - sm.should be < lg - lg.should be > sm - sm.should_not == lg + expect(sm).to be < lg + expect(lg).to be > sm + expect(sm).not_to eq(lg) end end @@ -106,7 +106,7 @@ describe Chef::Version do Chef::Version.new(s) end got = a.sort.map {|v| v.to_s } - got.should == %w{0.0.0 0.0.1 0.1.0 0.1.1 1.0.0 1.1.0 1.1.1} + expect(got).to eq(%w{0.0.0 0.0.1 0.1.0 0.1.1 1.0.0 1.1.0 1.1.1}) end it "should sort an array of versions, part 2" do @@ -114,7 +114,7 @@ describe Chef::Version do Chef::Version.new(s) end got = a.sort.map { |v| v.to_s } - got.should == %w{0.8.6 1.0.0 1.2.3 3.5.7 4.4.6 4.5.5 4.5.6 5.9.8 9.8.7} + expect(got).to eq(%w{0.8.6 1.0.0 1.2.3 3.5.7 4.4.6 4.5.5 4.5.6 5.9.8 9.8.7}) end describe "comparison examples" do @@ -163,7 +163,7 @@ describe Chef::Version do it "(#{spec.first(3).join(' ')}) should be #{spec[3]}" do got = Chef::Version.new(spec[0]).send(spec[1], Chef::Version.new(spec[2])) - got.should == spec[3] + expect(got).to eq(spec[3]) end end end diff --git a/spec/unit/version_constraint/platform_spec.rb b/spec/unit/version_constraint/platform_spec.rb index a3599aeb96..f38eb49689 100644 --- a/spec/unit/version_constraint/platform_spec.rb +++ b/spec/unit/version_constraint/platform_spec.rb @@ -21,24 +21,24 @@ describe Chef::VersionConstraint::Platform do it "is a subclass of Chef::VersionConstraint" do v = Chef::VersionConstraint::Platform.new - v.should be_an_instance_of(Chef::VersionConstraint::Platform) - v.should be_a_kind_of(Chef::VersionConstraint) + expect(v).to be_an_instance_of(Chef::VersionConstraint::Platform) + expect(v).to be_a_kind_of(Chef::VersionConstraint) end it "should work with Chef::Version::Platform classes" do vc = Chef::VersionConstraint::Platform.new("1.0") - vc.version.should be_an_instance_of(Chef::Version::Platform) + expect(vc.version).to be_an_instance_of(Chef::Version::Platform) end describe "include?" do it "pessimistic ~> x" do vc = Chef::VersionConstraint::Platform.new "~> 1" - vc.should include "1.3.3" - vc.should include "1.4" + expect(vc).to include "1.3.3" + expect(vc).to include "1.4" - vc.should_not include "2.2" - vc.should_not include "0.3.0" + expect(vc).not_to include "2.2" + expect(vc).not_to include "0.3.0" end end diff --git a/spec/unit/version_constraint_spec.rb b/spec/unit/version_constraint_spec.rb index dfa4740d51..0ae502f66d 100644 --- a/spec/unit/version_constraint_spec.rb +++ b/spec/unit/version_constraint_spec.rb @@ -26,18 +26,18 @@ describe Chef::VersionConstraint do v_error = Chef::Exceptions::InvalidCookbookVersion bad_version.each do |s| it "should raise #{v_error} when given #{s}" do - lambda { Chef::VersionConstraint.new s }.should raise_error(v_error) + expect { Chef::VersionConstraint.new s }.to raise_error(v_error) end end bad_op.each do |s| it "should raise #{o_error} when given #{s}" do - lambda { Chef::VersionConstraint.new s }.should raise_error(o_error) + expect { Chef::VersionConstraint.new s }.to raise_error(o_error) end end it "should interpret a lone version number as implicit = OP" do vc = Chef::VersionConstraint.new("1.2.3") - vc.to_s.should == "= 1.2.3" + expect(vc.to_s).to eq("= 1.2.3") end it "should allow initialization with [] for back compatibility" do @@ -52,28 +52,28 @@ describe Chef::VersionConstraint do it "should default to >= 0.0.0" do vc = Chef::VersionConstraint.new - vc.to_s.should == ">= 0.0.0" + expect(vc.to_s).to eq(">= 0.0.0") end it "should default to >= 0.0.0 when initialized with nil" do - Chef::VersionConstraint.new(nil).to_s.should == ">= 0.0.0" + expect(Chef::VersionConstraint.new(nil).to_s).to eq(">= 0.0.0") end it "should work with Chef::Version classes" do vc = Chef::VersionConstraint.new("1.0") - vc.version.should be_an_instance_of(Chef::Version) + expect(vc.version).to be_an_instance_of(Chef::Version) end it "should allow ops without space separator" do - Chef::VersionConstraint.new("=1.2.3").should eql(Chef::VersionConstraint.new("= 1.2.3")) - Chef::VersionConstraint.new(">1.2.3").should eql(Chef::VersionConstraint.new("> 1.2.3")) - Chef::VersionConstraint.new("<1.2.3").should eql(Chef::VersionConstraint.new("< 1.2.3")) - Chef::VersionConstraint.new(">=1.2.3").should eql(Chef::VersionConstraint.new(">= 1.2.3")) - Chef::VersionConstraint.new("<=1.2.3").should eql(Chef::VersionConstraint.new("<= 1.2.3")) + expect(Chef::VersionConstraint.new("=1.2.3")).to eql(Chef::VersionConstraint.new("= 1.2.3")) + expect(Chef::VersionConstraint.new(">1.2.3")).to eql(Chef::VersionConstraint.new("> 1.2.3")) + expect(Chef::VersionConstraint.new("<1.2.3")).to eql(Chef::VersionConstraint.new("< 1.2.3")) + expect(Chef::VersionConstraint.new(">=1.2.3")).to eql(Chef::VersionConstraint.new(">= 1.2.3")) + expect(Chef::VersionConstraint.new("<=1.2.3")).to eql(Chef::VersionConstraint.new("<= 1.2.3")) end it "should allow ops with multiple spaces" do - Chef::VersionConstraint.new("= 1.2.3").should eql(Chef::VersionConstraint.new("= 1.2.3")) + expect(Chef::VersionConstraint.new("= 1.2.3")).to eql(Chef::VersionConstraint.new("= 1.2.3")) end describe "include?" do @@ -82,70 +82,70 @@ describe Chef::VersionConstraint do @vc = Chef::VersionConstraint.new "> 1.2.3" end it "String" do - @vc.should include "1.4" + expect(@vc).to include "1.4" end it "Chef::Version" do - @vc.should include Chef::Version.new("1.4") + expect(@vc).to include Chef::Version.new("1.4") end it "Chef::CookbookVersion" do cv = Chef::CookbookVersion.new("alice", '/tmp/blah.txt') cv.version = "1.4" - @vc.should include cv + expect(@vc).to include cv end end it "strictly less than" do vc = Chef::VersionConstraint.new "< 1.2.3" - vc.should_not include "1.3.0" - vc.should_not include "1.2.3" - vc.should include "1.2.2" + expect(vc).not_to include "1.3.0" + expect(vc).not_to include "1.2.3" + expect(vc).to include "1.2.2" end it "strictly greater than" do vc = Chef::VersionConstraint.new "> 1.2.3" - vc.should include "1.3.0" - vc.should_not include "1.2.3" - vc.should_not include "1.2.2" + expect(vc).to include "1.3.0" + expect(vc).not_to include "1.2.3" + expect(vc).not_to include "1.2.2" end it "less than or equal to" do vc = Chef::VersionConstraint.new "<= 1.2.3" - vc.should_not include "1.3.0" - vc.should include "1.2.3" - vc.should include "1.2.2" + expect(vc).not_to include "1.3.0" + expect(vc).to include "1.2.3" + expect(vc).to include "1.2.2" end it "greater than or equal to" do vc = Chef::VersionConstraint.new ">= 1.2.3" - vc.should include "1.3.0" - vc.should include "1.2.3" - vc.should_not include "1.2.2" + expect(vc).to include "1.3.0" + expect(vc).to include "1.2.3" + expect(vc).not_to include "1.2.2" end it "equal to" do vc = Chef::VersionConstraint.new "= 1.2.3" - vc.should_not include "1.3.0" - vc.should include "1.2.3" - vc.should_not include "0.3.0" + expect(vc).not_to include "1.3.0" + expect(vc).to include "1.2.3" + expect(vc).not_to include "0.3.0" end it "pessimistic ~> x.y.z" do vc = Chef::VersionConstraint.new "~> 1.2.3" - vc.should include "1.2.3" - vc.should include "1.2.4" + expect(vc).to include "1.2.3" + expect(vc).to include "1.2.4" - vc.should_not include "1.2.2" - vc.should_not include "1.3.0" - vc.should_not include "2.0.0" + expect(vc).not_to include "1.2.2" + expect(vc).not_to include "1.3.0" + expect(vc).not_to include "2.0.0" end it "pessimistic ~> x.y" do vc = Chef::VersionConstraint.new "~> 1.2" - vc.should include "1.3.3" - vc.should include "1.4" + expect(vc).to include "1.3.3" + expect(vc).to include "1.4" - vc.should_not include "2.2" - vc.should_not include "0.3.0" + expect(vc).not_to include "2.2" + expect(vc).not_to include "0.3.0" end end @@ -153,13 +153,13 @@ describe Chef::VersionConstraint do it 'shows a patch-level if one is given' do vc = Chef::VersionConstraint.new '~> 1.2.0' - vc.to_s.should == '~> 1.2.0' + expect(vc.to_s).to eq('~> 1.2.0') end it 'shows no patch-level if one is not given' do vc = Chef::VersionConstraint.new '~> 1.2' - vc.to_s.should == '~> 1.2' + expect(vc.to_s).to eq('~> 1.2') end end @@ -167,13 +167,13 @@ describe Chef::VersionConstraint do it 'shows a patch-level if one is given' do vc = Chef::VersionConstraint.new '~> 1.2.0' - vc.inspect.should == '(~> 1.2.0)' + expect(vc.inspect).to eq('(~> 1.2.0)') end it 'shows no patch-level if one is not given' do vc = Chef::VersionConstraint.new '~> 1.2' - vc.inspect.should == '(~> 1.2)' + expect(vc.inspect).to eq('(~> 1.2)') end end end diff --git a/spec/unit/windows_service_spec.rb b/spec/unit/windows_service_spec.rb index ba3d2980df..cf933a9ab2 100644 --- a/spec/unit/windows_service_spec.rb +++ b/spec/unit/windows_service_spec.rb @@ -25,29 +25,29 @@ describe "Chef::Application::WindowsService", :windows_only do let (:shell_out_result) {Object.new} let (:tempfile) {Tempfile.new "log_file"} before do - instance.stub(:parse_options) - shell_out_result.stub(:stdout) - shell_out_result.stub(:stderr) + allow(instance).to receive(:parse_options) + allow(shell_out_result).to receive(:stdout) + allow(shell_out_result).to receive(:stderr) end it "runs chef-client in new process" do - instance.should_receive(:configure_chef).twice + expect(instance).to receive(:configure_chef).twice instance.service_init - instance.should_receive(:run_chef_client).and_call_original - instance.should_receive(:shell_out).and_return(shell_out_result) - instance.stub(:running?).and_return(true, false) - instance.instance_variable_get(:@service_signal).stub(:wait) - instance.stub(:state).and_return(4) + expect(instance).to receive(:run_chef_client).and_call_original + expect(instance).to receive(:shell_out).and_return(shell_out_result) + allow(instance).to receive(:running?).and_return(true, false) + allow(instance.instance_variable_get(:@service_signal)).to receive(:wait) + allow(instance).to receive(:state).and_return(4) instance.service_main end it "passes config params to new process" do Chef::Config.merge!({:log_location => tempfile.path, :config_file => "test_config_file", :log_level => :info}) - instance.should_receive(:configure_chef).twice + expect(instance).to receive(:configure_chef).twice instance.service_init - instance.stub(:running?).and_return(true, false) - instance.instance_variable_get(:@service_signal).stub(:wait) - instance.stub(:state).and_return(4) - instance.should_receive(:run_chef_client).and_call_original - instance.should_receive(:shell_out).with("chef-client --no-fork -c test_config_file -L #{tempfile.path}").and_return(shell_out_result) + allow(instance).to receive(:running?).and_return(true, false) + allow(instance.instance_variable_get(:@service_signal)).to receive(:wait) + allow(instance).to receive(:state).and_return(4) + expect(instance).to receive(:run_chef_client).and_call_original + expect(instance).to receive(:shell_out).with("chef-client --no-fork -c test_config_file -L #{tempfile.path}").and_return(shell_out_result) instance.service_main tempfile.unlink end diff --git a/spec/unit/workstation_config_loader_spec.rb b/spec/unit/workstation_config_loader_spec.rb index de108ff6d7..0f60e3ec38 100644 --- a/spec/unit/workstation_config_loader_spec.rb +++ b/spec/unit/workstation_config_loader_spec.rb @@ -177,7 +177,7 @@ describe Chef::WorkstationConfigLoader do env["CD"] = "/home/someuser/prod/chef-repo" # windows env["PWD"] = "/home/someuser/prod/chef-repo" # unix - Dir.stub(:pwd).and_return("/home/someuser/codes/chef-repo") + allow(Dir).to receive(:pwd).and_return("/home/someuser/codes/chef-repo") end it "loads the config from the non-dereferenced directory path" do |