PerlerのRuby日記

Rubyとか

SidekiqのWorkerクラス内でJobIDを知る

Sidekiq::Workerをincludeして使っているクラス内のperformメソッド内で自分のJobIDを知るには、self.jidで取れる。

class MyWorker
  include Sidekiq::Worker

  def perform
    job_id = self.jid
    puts job_id
    # some codes
  end
end

job_id = MyWorker.perform_async


なので、Sidekiqに登録したJobIDを、そのままworkerの処理結果のキーとして使えば結果の取得が簡単だ。

親メソッドのテスト

よくわからなくなったのでメモ。



メソッドを作ったのでテストを書く。

class H
  def hoge(flag)
    if flag
      "hogehoge"
    else
      "hoge"
    end
  end
end
describe H do
  describe "#hoge" do
    subject{ H.new.hoge(flag) }
    context "when flag is true" do
      let(:flag){ true }
      it{ should eq "hogehoge" }
    end
    context "when flag is false" do
      let(:flag){ false }
      it{ should eq "hoge" }
    end
  end
end


この後、このH#hogeを呼び出すメソッドを作ったときにそのメソッドのテストは、hogeのflagにまで言及すべきなのだろうか。

class H
  def hoge(flag)
    if flag
      "hogehoge"
    else
      "hoge"
    end
  end

  def h(flag)
    [hoge(flag)]
  end
end
describe H do
  describe "#hoge" do
    subject{ H.new.hoge(flag) }
    context "when flag is true" do
      let(:flag){ true }
      it{ should eq "hogehoge" }
    end
    context "when flag is false" do
      let(:flag){ false }
      it{ should eq "hoge" }
    end
  end

  describe "#h" do
    subject(:h){ H.new }

    # このcontextは必要?
    context "when flag is true" do
      let(:flag){ true }
      specify{ expect(h.h(flag)).to eq ["hogehoge"] }
    end
  end

  describe "#h" do
    # それとも#hogeはもうテストしているから、もっと単純なテストの方がよいのか?
    subject(:h){ H.new.new(flag) }
    let(:flag){ true }
    it{ should eq [hoge(flag)] } # そのままhoge()を呼んでいる
  end
end


[hoge(flag)]で動的に期待値を出しているのは強引な感じがするけど、
このあとhogeメソッドの挙動が変わったときに、hの方のテストの修正までするのはちょっと面倒くさい。

hogeの方のテストでカバレッジは網羅できていて、hの方のテストでtrue/falseを試す必要があるのかどうか悩む。