user_stackoverflow
user_stackoverflow

Reputation: 754

How to make a stub return a hash value

I have a model and a method inside that defined as follows :

class Farm < ActiveRecord::Base
   def flags
    #has other code which returns a flag_details hash eg:
    # flag_details['flag1'] = true;
    # flag_details['flag2'] = false;
  end

end

Now I need to write a test to verify that a particular div is displayed based on the flags that are set/unset. And I want to write a stub to be able to return these flags and then test if the page is displaying the correct div. How do I correct the following code, to get what I intend:

  scenario "display div named flower when flag1 or flag2 is false" do
    farm.stub(:flags).and_return("flag1" => false, "flag2" => false)
    if !farm.flags['flag1'] || !farm.flags['flag2']
      expect(page).to have_selector('div.flower', text: "4" )
    end    
  end

I am a beginner in ruby, rails and rspec, so any help will be great. I also tried using the following method but it did not work:

farm.stub(:flags[]).with('flag1').and_return(false)
farm.stub(:flags[]).with('flag2').and_return(false)

I also checked this documentation (https://www.relishapp.com/rspec/rspec-mocks/v/2-4/docs/method-stubs) but did not get my answer. Any other links that could be helpful in this, are really appreciated!

Thanks!

Upvotes: 0

Views: 4248

Answers (2)

tomciopp
tomciopp

Reputation: 2752

First, get rid of the if conditional in your test. There is no reason to add control flow to a test. How stubbing works: Your test needs to call the flags method on that farm object and it will return the hash that you have specified. Have your scenario visit the page in question and then check to make sure the expectation is behaving as you have intended.

Upvotes: 2

theTRON
theTRON

Reputation: 9649

I think you should just be able to wrap that return value in curly braces ({}) and it should solve your problem:

farm.stub(:flags).and_return({"flag1" => false, "flag2" => false})

Upvotes: 4

Related Questions