rubyrspecrspec-expectations

In rspec what does a test that ends with 'to be' mean?


You can find an example at https://github.com/cloudfoundry/cloud_controller_ng/blob/c63d33c0b1c2298d49a0bad959222b9c3daba16a/spec/unit/controllers/services/service_instances_controller_spec.rb#L1748 :

The second test in this block shows this:

expect(last_response).to have_status_code 202
expect(decoded_response['entity']['guid']).to be
expect(decoded_response['entity']['status']).to eq 'queued'

I see that we're matching against a new instance of Matchers::BuiltIn::Be, but at this point it's hard to see what we're actually matching against.

Ruby 2.1.3, rspec 3.0.0, rspec-expectations 3.0.4


Solution

  • As per the be matchers documentation, expect(obj).to be this test passes if obj is truthy (not nil or false).

    expect(decoded_response['entity']['guid']).to be means as documentation said, if the value of decoded_response['entity']['guid'] is any object, but not nil or false, the test will pass.

    Here is a demo example :

    RSpec.describe "be matcher" do
      context "when object is truthy" do
        specify { expect(2).to be }
      end
      context "when object is not truthy" do
        specify { expect(nil).not_to be }
      end
    end
    

    Lets run this test :-

    [arup@Ruby]$ rspec --format d spec/a_spec.rb
    
    be matcher
      when object is truthy
        should be
      when object is not truthy
        should not be
    
    Finished in 0.00254 seconds (files took 0.42175 seconds to load)
    2 examples, 0 failures