Stuart
Stuart

Reputation: 55

Rspec: helper method to detect presence of form field

I want to test that my controller helper method honeypot_detected? will be true if the @params of a form field named birth_city is filled in.

Do I need to use mocks in order to test this?

helpers.rb:

def honeypot_detected?
  @params[:birth_city].present?
end

helpers_spec.rb

require 'spec_helper'

describe WindowWashers::Controllers::Shared::Helpers do
.
.
.
  before(:all) { @controller = ApplicationController.new }
    context "when honeypot_detected? is called" do
      it "returns true when birth_city is storing a value" do
        #Not sure how to represent :birth_city => 'Dallas     
        expect(honeypot_detected?).to be_true
      end
    end
  end
.
.
.
end

Upvotes: 0

Views: 221

Answers (2)

Paul Fioravanti
Paul Fioravanti

Reputation: 16793

Since you're checking values stored in an instance variable, you should be able to use assign to set it. I'm assuming your instance variable @params is just a hash, in which case you probably don't need to go so far as to use a test double like you might for a more complicated object:

describe '#honeypot_detected?' do
  let(:honeypot_detected) { helper.honeypot_detected? }

  context 'when birth_city present in params' do
    before { assign(:params, { birth_city: "Dallas" }) } 
    it 'returns true' do
      expect(honeypot_detected).to be_true
    end
  end

  context 'when birth_city absent from params' do
    before { assign(:params, { foo: "bar" }) }
    it 'returns false' do
      expect(honeypot_detected).to be_false
    end
  end
end

Upvotes: 1

usha
usha

Reputation: 29349

context "when honeypot_detected? is called" do
  it "returns true when birth_city is storing a value" do
    instance_variable_set(:@params, {:birth_city => "Dallas"})     
    expect(honeypot_detected?).to be_true
  end
end

Upvotes: 1

Related Questions