tawheed
tawheed

Reputation: 5821

testing for method arguments in rspec

I was wondering how I could test method with arguments in rspec. After reading some post on SO and google I quickly realized that should_recieve could do the trick. For some strange reason though it does not seem to work as expected. Is there a possibility that I am missing anything.

ruby code

def new app_name
end

spec.rb file

describe BackboneGenerator::CLI do

    before  do
        @cli = BackboneGenerator::CLI.new
    end

    subject { @cli }

       it { should_receive(:new).with(:app_name) }

error

Failure/Error: it { should_receive(:new).with(:app_name) }
       (#<RSpec::Core::ExampleGroup::Nested_2:0x007fe8b3c5a690>).new(:app_name)
           expected: 1 time with arguments: (:app_name)
           received: 0 times with arguments: (:app_name)

PS: I am very green to testing

Upvotes: 2

Views: 7270

Answers (1)

Neil Slater
Neil Slater

Reputation: 27207

The matcher should_receive doesn't quite do what you think. It is not used to assert parameters to your method being tested. It is instead used to assert that something you do in the test causes a specific call to occur indirectly - often to a class or method outside of the unit test. For example, you might want to assert that an expensive call to an IO method is called only once, or that it definitely uses the same filename you set up in the constructor of your class.

The way to test that certain parameters are accepted is generally to call your method in the test with those parameters, and make assertions about the results.

describe BackboneGenerator::CLI do

  before  do
    @cli = BackboneGenerator::CLI.new
  end

 subject { @cli }

 describe "#new" do

   it "should accept ( :app_name ) as a parameter" do
     expect { subject.new( :app_name ) }.to_not raise_error
     # Or, more usually:
     # result = subject.new( :app_name )
     # result.should *match_some_test_criteria*
   end

   it "should not accept ( :foo, :bar ) as parameters" do
     expect { subject.new( :foo, :bar ) }.to raise_error
   end

I don't think that was the specific test you were looking for, but hopefully it gives you a test code pattern to base your real tests on.

Upvotes: 2

Related Questions