Search code examples
rubyruby-on-rails-4rspecrspec-railsrspec2

how to write rspec for method


I have following code in programmability folder

module Programmability
  module Parameter
    class Input < Parameter::Base
      attr_reader :args

  def initialize(name, type, **args)
    super(name, type)
    @args = args
  end

  def value=(val)
    if val
      val = convert_true_false(val)
--- some code ----
    end
    @value = val
  end      


  def convert_true_false(val)
    return val unless @args[:limit] == 1
    if [:char].include?(@type) && val == 'true'
      'Y'
    elsif [:char].include?(@type) && val == 'false'
      'N'
    elsif [:bit].include?(@type) && val == 'true'
      1
    elsif [:bit].include?(@type) && val == 'false'
      0
    end
  end
end
  end
end

I am trying to write rspec for method convert_true_false. I am new to rspec. any help is appreciated.

I tried doing this

   context 'returns Y if passed true'
    input = Programmability::Parameter::Input.new(name, type, limit)

      it 'returns Y' do
        name = 'unregister_series'
        type = ':char'
        limit = 1

        expect(input.value = 'true' ).to eq('Y')
      end
  end

but its not picking up limit value. when it reaches convert_true_false method it comes out of it since @args[:limit] is nil

Thanks


Solution

  • The issue is that setters always return the value passed:

    class Test
      def foo=(foo)
        @foo = foo + 100
        return 42
      end
    end
    
    puts (Test.new.foo = 69) # 69
    

    To resolve it, simply check the value after you assigned it:

    # instead of
    expect(input.value = 'true').to eq 'Y'
    
    # do
    input.value = 'true'
    expect(input.value).to eq 'Y'