RSpec it_behaves_like降低了调试可见性



我有以下代码:

context 'user doesnt exists with that email' do
  let(:params) { original_params.merge(login: "nouser@example.org") }
  it_behaves_like '404'
  it_behaves_like 'json result'
  it_behaves_like 'auditable created'
end

它很枯燥,因为我也可以在其他环境中使用这些元素:

context 'user exists with that email' do
  it_behaves_like '200'
  it_behaves_like 'json result'
end

我的共享示例是:

...
RSpec.shared_examples "json result" do
  specify 'returns JSON' do
    api_call params, developer_header
    expect { JSON.parse(response.body) }.not_to raise_error
  end
end
...

好处是该规范可读性更强且干燥。规范失败指向的是shared_example文件,而不是原始规范。这很难调试。在login_api_spec:25处发生以下错误,但这是rsspecs的输出:

rspec ./spec/support/shared_examples/common_returns.rb:14 # /api/login GET /email user doesnt exists with that email behaves like 401 returns 401

如何继续编写干式和易于调试的rspec,有什么好的建议吗?

如果没有共享的示例,代码将更长,也不那么容易阅读:

context 'user doesnt exists with that email' do
  let(:params) { original_params.merge(login: "nouser@example.org") }
  specify "returns 404" do
    api_call params, developer_header
    expect(response.status).to eq(404)
  end
  specify 'returns JSON' do
    api_call params, developer_header
    expect { JSON.parse(response.body) }.not_to raise_error
  end
  specify 'creates an api call audit' do
    expect do
      api_call params, developer_header
    end.to change{ EncoreBackend::ApiCallAudit.count }.by(1)
  end
end

我有成千上万个这样的RSpec测试,所以用共享示例编写规范是非常有益的,因为它编写起来很快,但调试很难。

在详细的错误中,有这样的描述:

Shared Example Group: "restricted_for developers" called from ./spec/api/login_api_spec.rb:194

这告诉错误的确切位置

最新更新