ruby-on-railsruby-on-rails-3rspecrspec-railsrspec2

Write a RSpec test for method that takes a single argument


I need to write the RSpec test case for a module that has a private method and takes a single Argument.

module x
  private
  def fun(para)
  end
end

I have a spec file where I tried to write a case like this. para and params are the arguments we can say.

RSpec.describe x do
  class spec
    include x
    def initialize(params)
      @params = params
    end
  end

  describe "describe" do
    context "context" do
      it "should not truncate any normal text value" do
        obj = spec.new(params)
        # first 
        expect('dummy text').to obj.send(:fun).with(para)

        # second
        expect(obj).to receive(:fun).with(para);

        #third
        retr = obj.send(:fun).with(para);
        expect retr.to eq('dummy text')
      end
    end
  end
end

First, second and third, I used to get the output but these three ways didn’t work. They all are throwing some error. Guys, can you help me to understant what I'm doing wrong? How can I resolve this?


Solution

  • If a method is private you should not have to test it directly but in some cases, why not. 🙂 I don't know what your fun method is supposed to do but here is some help.

    RSpec.describe x do
      class MySpec
        include x
        def initialize(params)
          @params = params
        end
      end
    
      describe "#fun" do
        subject { my_spec.send(:fun).with(para) } 
    
        let(:my_spec) { MySpec.new(params) } 
        let(:params) { { foo: :bar } }
        let(:para) { 'dummy text' }
    
        it "should not truncate any normal text value" do
          expect(subject).to eq(para)
        end
      end
    end