Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RSpec's "expect" etc. outside a describe ... it block

Tags:

ruby

rspec

I'm building a web-app automation framework that is designed to allow for:

  • automating tasks, of course
  • building test scenarios easily

I'm using Capybara to communicate with a browser and I have a library of components with a number of helper functions (login_to_the_back_office, create_customer, etc.).

Now I would like my components to be usable standalone as well as within RSpec tests. This means that my components, as included in the library, are not wrapped around describe... it... blocks by default, but they will be at some point when a test uses them and so they should use expect and friends as often as possible.

I followed rspec's .should fails (outside describe/it block) in Ruby 2? to enable should and it works (actually just requiring rspec-expectations was enough in my case), but I can't figure out how to make expect work.

I think expect is defined here https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb but my knowledge of Ruby's meta-magic is too limited to figure out how to make expect available to my class.

I've tried including RSpec::Expectations::Syntax in my class but I still get undefined method 'expect' whenever I try to use it.

How can I use expect outside of describe... it... ?

like image 982
djfm Avatar asked May 13 '14 07:05

djfm


1 Answers

include ::RSpec::Matchers

class A
  include ::RSpec::Matchers
  def test
    expect('1'.to_i).to eq 1
  end

  def failed_test
    expect('1'.to_i).to eq 2
  end
end
A.new.test
# => true
A.new.failed_test
# RSpec::Expectations::ExpectationNotMetError: 
# expected: 2
#      got: 1
like image 148
Uri Agassi Avatar answered Oct 18 '22 20:10

Uri Agassi