LoginSignup
3
0

More than 3 years have passed since last update.

【Rails/RSpec】mockの戻り値はOpenStructを使えば仕事が捗る

Last updated at Posted at 2020-05-30

こういうコードに対して

class SomeClass
  include Service # これを include することで SomeClass.call(foo) という形で呼べるようにしています。↓のYourClassを同様です。

  def initialize(foo)
    @foo = foo
  end

  def call
    response = YourClass.call(@foo)
    unless response.success?
      raise StandardError, 'your error message comes here'
    end
    ...
  end
end

こういう mock と mock response を書く。

let(:mock_response) { OpenStruct.new(success?: true, body: { bar: 'bar' }.to_json) }

before do
  allow(YourClass).to receive(:call).and_return(mock_response)
end

異常系のテストをする時は、mock_responsesuccess?: false とする。

let(:mock_response) { OpenStruct.new(success?: false, body: { bar: 'bar' }.to_json) }
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0