2016-06-29 4 views
0

は私はこのようなモデルを持っている:私はdo_stuffが適切に右引数とmethod_onemethod_twoの方法を実行していることをテストするにはどうすればよい非ActiveRecordモデルをRailsにスタブする方法は?

class Thing 
    class << self 
    def do_stuff(param) 
     result1 = method_one(param) 
     result2 = method_two(result1) 
    end 

    def method_one(param) 
     # tranformation 
    end 

    def method_two(result1) 
     # transformation 
    end 
    end 
end 

?私はmock_model/mock_classを試してきましたが、それらは私には分かりません。私はドキュメントを読んだが、私はまだそれを理解するのに苦労している。

require 'rails_helper' 

RSpec.describe Thing, type: :model do 
    let!(:param) { create(:param) } 

    describe '#do_stuff' do 
    thing = double('thing') 
    expect(thing).to receive(:method_one).with param 
    thing.do_stuff param 
    end 
end 

なぜこれが動作しません。

私のテストでは、このようになりますか? 私が受け取るエラーは、予期せぬメッセージのパラメータを受け取ったことです。しかし、それはかなり期待され、それがテストでした。どこが間違っていますか?

答えて

2

私はあなたのモデルを倍にするべきではないと思います。例に続いて、私の作品:

class Thing 
    class << self 
    def do_stuff(param) 
     result1 = method_one(param) 
     result2 = method_two(result1) 
    end 

    def method_one(param) 
     param[:foo] 
    end 

    def method_two(result1) 
     # transformation 
     result1 
    end 
    end 
end 

# thing_spec.rb 
require 'rails_helper' 

RSpec.describe Thing, type: :model do 
    let!(:param) { {foo: "bar"} } 

    describe '#do_stuff' do 
    it 'should do stuff' do 
     expect(Thing).to receive(:method_one).with(param) 
     Thing.do_stuff param 
    end 
    end 
end 

テスト結果を正確に

[[email protected] ~/workspace/tapp]$ be rspec spec/models/thing_spec.rb 
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in <top (required)> at /Users/retgoat/workspace/tapp/config/environments/test.rb:16) 
. 

Finished in 0.0069 seconds (files took 1.78 seconds to load) 
1 example, 0 failures 
+0

。もっとsuccintlyするには、クラスメソッドはインスタンスではなくクラスに対してスタブされなければなりません。 – jaydel

+0

優秀ありがとう!それは理にかなっています(テストを実行する時間をとっていただければ幸いです)。 – user3162553

関連する問題