Skip to content

Instantly share code, notes, and snippets.

@jnicklas
Created November 22, 2012 08:14
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save jnicklas/4129937 to your computer and use it in GitHub Desktop.
Save jnicklas/4129937 to your computer and use it in GitHub Desktop.
require "timeout"
module WaitSteps
extend RSpec::Matchers::DSL
matcher :become_true do
match do |block|
begin
Timeout.timeout(Capybara.default_wait_time) do
sleep(0.1) until value = block.call
value
end
rescue TimeoutError
false
end
end
end
end
@agenteo
Copy link

agenteo commented Jan 6, 2015

in Rspec 3.1 you need to add a:

def supports_block_expectations?
  true
end

to the matcher

@oboxodo
Copy link

oboxodo commented Jun 24, 2016

I think become_truthy better reflects this method (semantic taken from Rspec's be_truthy). Here's my version and how I'm using it:

# Usage:
#
# it "should show email for a newly created user" do
#   email = "john@example.com"
#
#   visit new_user_path
#   fill_in "Email", with: email
#   fill_in "Password", with: "secret-password"
#   click_button "Save"
#
#   user = nil
#   expect { user = User.find_by(email: email) }.to become_truthy
#
#   visit user_path(user)
#
#   expect(page).to have_content(email)
# end

RSpec::Matchers.define :become_truthy do |event_name|
  supports_block_expectations

  match do |block|
    begin
      Timeout.timeout(Capybara.default_max_wait_time) do
        sleep(0.05) until value = block.call
        value
      end
    rescue TimeoutError
      false
    end
  end
end

@vbrazo
Copy link

vbrazo commented Sep 23, 2018

This become_truthy helped me here. I customized a bit and it's just perfect. Thanks.

# spec_helper.rb
RSpec::Matchers.define :wait_until do |event_name|
  supports_block_expectations

  match do |block|
    begin
      Timeout.timeout(Capybara.default_max_wait_time) do
        sleep(0.05) until value = block.call
        value
      end
    rescue TimeoutError
      false
    end
  end
end

# features/location_ajax_autocomplete_spec.rb
require 'rails_helper'

feature 'Products GET #location', type: :feature do
  context 'with valid params' do
    scenario 'populates location after requesting in the api' do
      visit location_path

      fill_in 'location', with: 'Munich'

      wait_until { expect(page.body).to have_selector('li', class: 'location-item', count: 10) }
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment