0

I am trying to write a Rspec test for a ruby function which lives in a new file and references an instance variable inside a controller file. I am having unable to mock anything for the line

flag = @domain.feature?("BrandNewFeature")

When I run the above code I get error on line

flag = @domain.feature?("BrandNewFeature") 

saying

#<NoMethodError: undefined method `feature?' for nil:NilClass>

Any help is greatly appreciated

play.rb

Api.controllers :playbooks do
before do
    @domain = account.domain

def get_filter(param)
    f = find_lists(param)

play_help.rb

module ApiHelpers
def find_lists(params)
    flag = @domain.feature?("BrandNewFeature")
    folder = ListQueries.folders(params) if flag
    folder

play_help_spec.rb

require "unit/spec_help"
require_project "api/helpers/play_help.rb"

RSpec.describe ApiHelp do

describe "#find_matching_lists" do
    allow(list_queries).to receive(:folders).and_return(folders)
    binding.pry
    domainDouble = double()
    allow(Domain).to receive(:new).and_return(domainDouble)

    allow(domainDouble).to receive(:feature?).with("BrandNewFeature").and_return(true)
2

1 Answer 1

0

When you cannot controll the instance that you need to mock then you can use allow_any_instance_of:

RSpec.describe ApiHelp do
  let(:folders) { ... }
  let(:params) { ... }

  before do 
    allow_any_instance_of(Domain)
      .to receive(:feature?).with('BrandNewFeature').and_return(true)
    allow(ListQueries)
      to receive(:folders).with(params).and_return(folders)
  end

  describe '#find_matching_lists' do
    expect(ApiHelp.get_filter).to eq(folders)

    expect_any_instance_of(Domain).to have_received(:feature?).once
    expect(ListQueries).to have_received(folders).once
  end
Sign up to request clarification or add additional context in comments.

4 Comments

Have you tried this scenario? Is this working for you? I am still getting an error.
What error do you get?
When I run the test, I see it errors out in play_help.rb. Also in the play_help.rb @domain is coming out Nil (I checked by utting binding.pry) => #<NoMethodError: undefined method `feature?' for nil:NilClass>
What is @domain in your helper?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.