Skip to content

Instantly share code, notes, and snippets.

@cpkenn09y
Last active October 8, 2019 22:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpkenn09y/287626c8c03bcd7834f266e4ecf00fb0 to your computer and use it in GitHub Desktop.
Save cpkenn09y/287626c8c03bcd7834f266e4ecf00fb0 to your computer and use it in GitHub Desktop.
## IMPORTANT -> The expectation must come before the invocation, so that it can catch the invocation when it happens
# Able to stub an instance's method. Will return whatever is in the block. The instance's method would have to be invoked in the RSpec.
@person.stub(:get_relevant_experts) { @collection_of_possibilities }
# Expectation of an instance that is available in the testing context to receive a particular method, choose return value
expect(@person).to receive(:get_relevant_experts).with("Medical").and_return(@collection_of_possibilities)
# Expectation of an instance to receive a method and return a result
expect_any_instance_of(Classification).to receive(:valid_matches).and_return(@collection_of_possibilities)
# Expectation of a class to receive a method
expect(ClassificationSystem).to receive(:choose_record_with_special_flag_or_unclassified_fallback)
# How to stub a constant within a class
stub_const("Api::V1::PublicationsController::DEFAULT_PAGINATION_COUNT", 1)
@cpkenn09y
Copy link
Author

cpkenn09y commented Sep 24, 2018

:: Given the scenario ::

  • An instance of Card receives "post_to_firebase" multiple times, was unable to make expect_any_instance_of accept a value for the number of times it should be invoked

FAILED: expect_any_instance_of(Card).to receive(:post_to_firebase).exactly(5).times # the clause "exactly" does not work for expect_any_instance_of
Success via: expect(FirebaseCard).to receive(:push).exactly(5).times

@ccECI
Copy link

ccECI commented Jul 12, 2019

# To allow expectations of 0 to N number of calls, the follow syntax allows them all
allow(FaradayUtility::Content).to receive(:add_survey).and_return(:success)

@cpkenn09y
Copy link
Author

cpkenn09y commented Aug 5, 2019

If you ever find that you are passing in a Boolean into a POST or PUT, and you notice that your Boolean is getting turned into a String...

For example:
true -> becoming a String of “true”

**Make sure to use request.content_type = 'application/json' in your spec

@cpkenn09y
Copy link
Author

Incase you see other specs that break intermittently...

It has a decently high likelihood to be due to:

  1. expecting that AR will automatically return records in order of id (self.survey_results .vs. self.survey_results.order(:id))
  2. DateTime objects needing to be stubbed properly
  3. ENV variables getting set in a spec, then specs after are adversely affected (eg. settings.yml values, Rails.env, or other initializer values)

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