How to lock an instance method only if the value of the instance variable matters?

I have a MyObject object:

 class MyObject def initialize(options = {}) @stat_to_load = options[:stat_to_load] || 'test' end def results [] end end 

I want to stat_to_load = "times" results method only if stat_to_load = "times" . How can i do this? I tried:

 MyObject.any_instance.stubs(:initialize).with({ :stat_to_load => "times" }).stubs(:results).returns(["klala"]) 

but that will not work. Any idea?

+6
source share
3 answers

So, I think there is probably an easier way to verify that you are trying to test, but without additional context, I don’t know what to recommend. However, here is the code for the evidence-based concept to show what you can do:

 describe "test" do class TestClass attr_accessor :opts def initialize(opts={}) @opts = opts end def bar [] end end let!(:stubbed) do TestClass.new(args).tap{|obj| obj.stub(:bar).and_return("bar")} end let!(:unstubbed) { TestClass.new(args) } before :each do TestClass.stub(:new) do |args| case args when { :foo => "foo" } stubbed else unstubbed end end end subject { TestClass.new(args) } context "special arguments" do let(:args) { { :foo => "foo" } } its(:bar) { should eq "bar" } its(:opts) { should eq({ :foo => "foo" }) } end context "no special arguments" do let(:args) { { :baz => "baz" } } its(:bar) { should eq [] } its(:opts) { should eq({ :baz => "baz" }) } end end 

 test special arguments bar should == bar opts should == {:foo=>"foo"} no special arguments bar should == [] opts should == {:baz=>"baz"} Finished in 0.01117 seconds 4 examples, 0 failures 

However, I very often use special themes / context blocks. See http://benscheirman.com/2011/05/dry-up-your-rspec-files-with-subject-let-blocks/ for more details.

0
source

Try below, this should work as expected:

Here, basically, we are actually completing the creation of a new instance by creating, as well as stubbing results method of the returned instance.

 options = {:stat_to_load => "times"} MyObject.stubs(:new).with(options) .returns(MyObject.new(options).stubs(:results).return(["klala"])) 
0
source

To achieve this, you can use plain old Ruby inside your test.

 MyObject.class_eval do alias_method :original_results, :results define_method(:results?) do if stats_to_load == "times" ["klala"] else original_results end end end 
0
source

Source: https://habr.com/ru/post/946091/


All Articles