rubyrspecrspec-expectations

How can I use RSpec Expectations in PORO's


Hi,

I am trying to DRY up some of my specs. I extracted an Assertion class that does a couple of shoulds ... but most of the RSpec expectation magic is not working anymore.

I'll try to construct a simple example, to show my problem.

The object under test:

class Foo
  def has_bar?; true; end
end

My assertion class:

class MyAssertions
  def self.assert_everything_is_ok
    @foo = Foo.new
    @foo.has_bar?.should == true  # works!
    @foo.has_bar?.should be_true  # undefined local variable or method `be_true`
    @foo.should have_bar          # undefined local variable or method `have_bar`
  end
end

My spec:

it "tests something" do
  @foo = Foo.new
  @foo.should have_bar                # works!
  MyAssertion.assert_everything_is_ok # does not work, because of errors above
end

Why can I not use the syntactic sugar of rspec expectations in my plain old ruby object?


Solution

  • After some more trying I came up with this solution:

    class MyAssertions
      include RSpec::Matchers
    
      def assert_everything_is_ok
        @foo = Foo.new
        @foo.has_bar?.should == true  # works!
        @foo.has_bar?.should be_true  # works now :)
        @foo.should have_bar          # works now :)
      end
    end
    

    The trick was to include the RSpec::Matchers module. And I had use instance methods instead of class methods.