1

我喜欢 Trailblazer 的所有面向对象的美!

我有一个与 gem(称为cpanel_deployer)交互的操作,以在网络上进行外部操作。(它将插件域添加到 cpanel。)

class Website::Deploy < Trailblazer::Operation
  attr_reader :website, :cpanel

  def process(params)
    real_cpanel_add_domain
    website.cpanel = cpanel
    website.save
  end

  private

  def setup!(params)
    @cpanel = Cpanel.find(params[:cpanel_id])
    @website = website.find(params[:website_id])
  end

  def real_cpanel_add_domain
    cp_domain = CpanelDeployer::Domain.new(website.domain)
    cp_panel = CpanelDeployer::Panel.new(cpanel.host, cpanel.username, cpanel.password)

    res = cp_panel.add_domain(cp_domain)

    raise StandardError unless res
  end

end

cpanel_deloyergem 已经过测试,所以我不需要在这里重新测试它的功能。但为了测试操作,我想确保CpanelDeployer::Panel#add_domain使用正确的参数调用。所以我想我应该嘲笑CpanelDeployer::Panel

我认为尝试使用any_instance_of. 根据thoughtbot 的说法,它通常被认为是代码异味......他们建议使用依赖注入。有没有一种在开拓者操作中使用依赖注入的好方法?这种情况还有另一种最佳做法吗?

4

2 回答 2

0

老实说,我真的不明白real_cpanel_add_domain在做什么,因为在我看来,它只是分配了两个局部变量,然后调用add_domain其中一个,这将如何影响任何事情?

说到依赖注入,我猜你可以从 获取域和面板类params,默认为CpanelDeployer::Domainand CpanelDeployer::Panel,但在你的规范中传递一些存根。

我不是存根new方法的忠实拥护者,因为它并不总是按预期工作。

于 2016-02-26T10:04:14.547 回答
0

一种选择是存根:newgem 的类并返回测试替身。看起来是这样的:

  describe Website::Deploy do

    let(:cpanel) { Cpanel::Create.(cpanel: {
      host: 'cpanel-domain.com', username: 'user', password: 'pass'
    }).model }

    let(:website) { Website::Create.(website: { domain: 'domain.com' }).model }

    it 'works' do
      fake_cp_domain = double(CpanelDeployer::Domain)
      fake_cp = double(CpanelDeployer::Panel)

      expect(fake_cp).to receive(:add_domain).with(fake_cp_domain).and_return(true)

      expect(CpanelDeployer::Domain).to receive(:new)
        .with(website.domain)
        .and_return(fake_cp_domain)

      expect(CpanelDeployer::Panel).to receive(:new)
        .with(cpanel.host, cpanel.username, cpanel.password)
        .and_return(fake_cp)

      Website::Deploy.(cpanel_id: cpanel.id, website_id: website.id)
    end
  end

这看起来很麻烦......有更好的方法吗?

于 2016-02-26T00:03:56.533 回答