Last active
December 27, 2015 06:39
-
-
Save simsalabim/7282646 to your computer and use it in GitHub Desktop.
How to stub Capybara's `page#source`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # First, there is another (simple) way to accomplish the task and I would suggest to never use approach shown below. I mean stub page#source. | |
| # | |
| # Given there are several steps which rely on `page#source`, for instance checking contents of downloaded CSV file. | |
| # And we decided to store several CSV files in the cloud | |
| # And we still want to test their contents | |
| # Then we test output of file generators | |
| # But we want to reuse and DO NOT TOUCH existing steps checking CSV files contents | |
| # Then we decide to stub page#source | |
| # Simple solution, nothing interesting here, you can skip it. | |
| def check_csv_contents(csv, cucumber_table) | |
| ... | |
| end | |
| Then /^the CSV file contents should match:$/ do |table| | |
| csv = CSV.generate { |csv| csv << %w(tom and jerry) } # real CSV generation should be preformed here | |
| check_csv_contents csv, table | |
| end | |
| Then /^old CSV checking step relied on page#source:$/ do |table| | |
| check_csv_contents page.source, table | |
| end | |
| # BORING!!! | |
| # B O R I N G ! ! ! | |
| # An amused alternative, please never do like that :) | |
| Then /^the CSV file contents should match:$/ do |table| | |
| csv = CSV.generate { |csv| csv << %w(tom and jerry) } # real CSV generation should be preformed here | |
| new_source_module = Module.new do | |
| define_method :new_source do | |
| csv | |
| end | |
| end | |
| page.instance_eval do | |
| self.class.send :include, new_source_module | |
| # we need to keep an eye on the original "page#source" to release our stub in the future | |
| self.class.send :alias_method, :old_source, :source unless respond_to?(:old_source) | |
| self.class.send :alias_method, :source, :new_source | |
| end | |
| end | |
| Then /^crazy extra step to unstub page#source$/ do | |
| page.instance_eval do | |
| self.class.send :alias_method, :source, :old_source | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment