Skip to content

Instantly share code, notes, and snippets.

@theoretick
Created July 18, 2013 21:21
Show Gist options
  • Save theoretick/6033200 to your computer and use it in GitHub Desktop.
Save theoretick/6033200 to your computer and use it in GitHub Desktop.
####################################################
# Rspec matchers/expectations
####################################################
##USE EXPECT(foo) NOT (foo).SHOULD
```ruby
expect(foo).to eq(bar)
(foo).should eq(bar) # deprecated(ish) see below
```
##WHY EXPECT?
- ``expect`` unifies block and value syntax
- ``expect`` does not monkeypatch every obj, ``should`` does
("for should to work properly, it must be defined on every object in the
system… but RSpec does not own every object in the system and cannot
ensure that it always works consistently")
####################################################
# 1 'describe' per Class/Module
# 1 'describe' per Function/Method
# 1 'it' per use-case test
```ruby
describe ClassName do
it "describes this codeblock for human debugging" do
# tests here
end
end
```
####################################################
####################################################
##Equivalence
```ruby
expect(foo).to eq(bar)
expect(foo).to eql(bar)
expect(foo).not_to eq(bar)
expect(foo).not_to eql(bar)
expect(2+3).to eq(5)
expect(2+3).not_to eq(23)
```
##Identity
```ruby
expect(foo).to be(bar)
expect(foo).to equal(bar)
expect(:split).to be(:split)
```
##Comparisons
```ruby
expect(foo).to be > bar
expect(foo).to be >= bar
expect(foo).to be <= bar
expect(foo).to be < bar
expect(foo).to be_within(delta).of(bar)
expect(my_age).to be < fathers_age
```
##Regular Expressions (Regex)
```ruby
expect(foo).to match(/expression/)
expect('hello world').to match(/^(hello|hi)/)
```
##Types & Classes
```ruby
expect(foo).to be_an_instance_of(expected)
expect(foo).to be_a_kind_of(expected)
expect(@discussit).to be_an_instance_of(DiscussIt)
```
##Truthiness (Booleans)
```ruby
expect(foo).to be_true # passes if foo is truthy (not nil or false)
expect(foo).to be_false # passes if foo is falsy (nil or false)
expect(foo).to be_nil # passes if foo is nil
expect(user_name.valid?).to be_true
```
## Errors
```ruby
expect { ... }.to raise_error
expect { ... }.to raise_error(ErrorClass)
expect { ... }.to raise_error("message")
expect { ... }.to raise_error(ErrorClass, "message")
expect { 'hello'.match(/^he/,/^bar/)}.to raise_error(ArgumentError, "wrong number of arguments (2 for 1)")
```
## Throws
```ruby
expect { ... }.to throw_symbol
expect { ... }.to throw_symbol(:symbol)
expect { ... }.to throw_symbol(:symbol, 'value')
```
## Yielding
```ruby
expect { |b| 5.tap(&b) }.to yield_control # passes regardless of yielded args
expect { |b| yield_if_true(true, &b) }.to yield_with_no_args # passes only if no args are yielded
expect { |b| 5.tap(&b) }.to yield_with_args(5)
expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum)
expect { |b| "a string".tap(&b) }.to yield_with_args(/str/)
expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3)
expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2])
```
## Predicate matchers
```ruby
expect(foo).to be_xxx # passes if foo.xxx?
expect(foo).to have_xxx(:arg) # passes if foo.has_xxx?(:arg)
```
## Ranges
```ruby
expect(RangeXtoZ).to cover(Y)
expect(1..10).to cover(3)
```
## Collection membership & Sets
```ruby
expect(foo).to include(expected)
expect(foo).to start_with(expected)
expect(foo).to end_with(expected)
expect('hello').to start_with('h')
```
 
## Rendering
```ruby
expect(response).to render_template(:index)
```
 
## Redirecting
```ruby
expect(response).to redirect_to(movies_path)
```
 
#Capybara
## Capybara Matchers
http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Matchers
```ruby
expect(current_path).to eq(user_profile_path(profile))
expect(response.body).to eq(other)
expect(response.body).to assert_no_selector(*args)
Asserts that a given selector is not on the page or current node.
expect(response.body).to assert_selector(*args)
Asserts that a given selector is on the page or current node.
expect(response.body).to has_button?(locator)
Checks if the page or current node has a button with the given text, value or id.
expect(response.body).to has_checked_field?(locator)
Checks if the page or current node has a radio button or checkbox with the given label, value or id, that is currently checked.
expect(response.body).to has_css?(path, options = {})
Checks if a given CSS selector is on the page or current node.
expect(response.body).to has_field?(locator, options = {})
Checks if the page or current node has a form field with the given label, name or id.
expect(response.body).to has_link?(locator, options = {})
Checks if the page or current node has a link with the given text or id.
expect(response.body).to has_no_button?(locator)
Checks if the page or current node has no button with the given text, value or id.
expect(response.body).to has_no_checked_field?(locator)
Checks if the page or current node has no radio button or checkbox with the given label, value or id, that is currently checked.
expect(response.body).to has_no_css?(path, options = {})
Checks if a given CSS selector is not on the page or current node.
expect(response.body).to has_no_field?(locator, options = {})
Checks if the page or current node has no form field with the given label, name or id.
expect(response.body).to has_no_link?(locator, options = {})
Checks if the page or current node has no link with the given text or id.
expect(response.body).to has_no_select?(locator, options = {})
Checks if the page or current node has no select field with the given label, name or id.
expect(response.body).to has_no_selector?(*args)
Checks if a given selector is not on the page or current node.
expect(response.body).to has_no_table?(locator, options = {})
Checks if the page or current node has no table with the given id or caption.
expect(response.body).to has_no_text?(*args) (also: #has_no_content?)
Checks if the page or current node does not have the given text content, ignoring any HTML tags and normalizing whitespace.
expect(response.body).to has_no_unchecked_field?(locator)
Checks if the page or current node has no radio button or checkbox with the given label, value or id, that is currently unchecked.
expect(response.body).to has_no_xpath?(path, options = {})
Checks if a given XPath expression is not on the page or current node.
expect(response.body).to has_select?(locator, options = {})
Checks if the page or current node has a select field with the given label, name or id.
expect(response.body).to has_selector?(*args)
Checks if a given selector is on the page or current node.
expect(response.body).to has_table?(locator, options = {})
Checks if the page or current node has a table with the given id or caption:.
expect(response.body).to has_text?([type], text, [options]) (also: #has_content?)
Checks if the page or current node has the given text content, ignoring any HTML tags and normalizing whitespace.
expect(response.body).to has_unchecked_field?(locator)
Checks if the page or current node has a radio button or checkbox with the given label, value or id, that is currently unchecked.
expect(response.body).to has_xpath?(path, options = {})
Checks if a given XPath expression is on the page or current node.
```
## Capybara DSL
## Navigation
```ruby
visit('/users') # visit always uses GET request
visit(user_show_path) #
expect(current_path).to eq(post_comments_path(post))
```
## links and buttons
```ruby
click_on('Link Text') # clicks on either links or buttons
click_link('id-of-link')
click_link('Link Text')
click_button('Save')
click_on('Button Value')
```
## forms
```ruby
fill_in('First Name', :with => 'John')
fill_in('Password', :with => 'Seekrit')
fill_in('Description', :with => 'Really Long Text...')
choose('A Radio Button')
check('A Checkbox')
uncheck('A Checkbox')
attach_file('Image', '/path/to/image.jpg')
select('Option', :from => 'Select Box')
```
## locating or finding
```ruby
find_field('First Name').value
find_link('Hello').visible?
find_button('Send').click
find(:xpath, "//table/tr").click
find("#overlay").find("h1").click
all('a').each { |a| a[:href] }
find('#navigation').click_link('Home')
find('#navigation').should have_button('Sign out')
```
## existence
```ruby
expect(page).to have_selector('table tr')
expect(page).to have_selector(:xpath, '//table/tr')
expect(page).to have_xpath('//table/tr')
expect(page).to have_css('table tr.foo')
expect(page).to have_content('foo')
```
## scoping actions
### NOTE - only interacts with FIRST element matched, not any
```ruby
within("li#employee") do
fill_in 'Name', :with => 'Jimmy'
end
within(:xpath, "//li[@id='employee']") do
fill_in 'Name', :with => 'Jimmy'
end
```
####################################################
#using rspec in IRB
####################################################
> require 'rspec'
> inc RSpec::Matchers
> expect('hello').to start_with('h')
=> true
http://stackoverflow.com/questions/14749047/how-to-use-rspec-expectations-in-irb
####################################################
them0nk / rspec_rails_cheetsheet.rb
https://gist.github.com/them0nk/2166525
####################################################
#Model
 
@user.should have(1).error_on(:username) # Checks whether there is an error in username
@user.errors[:username].should include("can't be blank") # check for the error message
 
 
#Capybara Matchers
 
expect(response.body).to have_content("Hello world")
expect(response.body).to have_no_content("Hello world")
 
expect(response.body).to have_css("input#movie_title")
expect(response.body).to have_css("input#movie_title", :value => "Twelve Angry Men")
expect(response.body).to have_css("input", :count => 3) #True if there are 3 input tags in response
expect(response.body).to have_css("input", :maximum => 3) # True if there or fewer or equal to 3 input tags
expect(response.body).to have_css("input", :minimum => 3) # True if there are minimum of 3 input tags
expect(response.body).to have_css("input", :between => 1..3) # True if there 1 to 3 input tags
expect(response.body).to have_css("p a", :text => "hello") # True if there is a anchor tag with text hello
expect(response.body).to have_css("p a", :text => /[hH]ello(.+)/i)
# True if there is a anchor tag with text matching regex
 
expect(response.body).to have_xpath("//a")
expect(response.body).to have_xpath("//a",:href => "google.com")
expect(response.body).to have_xpath("//a[@href => 'google.com']")
expect(response.body).to have_xpath("//a[contains(.,'some string')]")
expect(response.body).to have_xpath("//p//a", :text => /re[dab]i/i, :count => 1)
 
 
# can take both xpath and css as input and can take arguments similar to both have_css and have_xpath
expect(response.body).to have_selector(:xpath, "//p/h1")
expect(response.body).to have_selector(:css, "p a#movie_edit_path")
 
# For making capybara to take css as default selector
Capybara.default_selector = :css
expect(response.body).to have_selector("input") #checks for the presence of the input tag
expect(response.body).to have_selector("input", :value =>"Twelve Angry Men") # checks for input tag with value
expect(response.body).to have_no_selector("input")
 
# For making capybara to take css as default selector
Capybara.default_selector = :xpath
expect(response.body).to have_selector("//input") #checks for the presence of the input tag
expect(response.body).to have_selector("//input", :value =>"Twelve Angry Men") # checks for input tag with value
 
 
# To access elements inside form
expect(response.body).to have_field("FirstName") # checks for presence of a input field named FirstName in a form
expect(response.body).to have_field("FirstName", :value => "Rambo")
expect(response.body).to have_field("FirstName", :with => "Rambo")
 
expect(response.body).to have_link("Foo")
expect(response.body).to have_link("Foo", :href=>"googl.com")
expect(response.body).to have_no_link("Foo", :href=>"google.com")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment