【问题标题】:Unable to call a method inside RSpec Shared Example无法在 RSpec 共享示例中调用方法
【发布时间】:2019-08-08 12:02:45
【问题描述】:

尝试使用 RSpec 共享示例测试无效的授权标头。

下面是代码

describe 'PUT#update' do
let(:account) do
  account = build(:account)
  account.save!
  account
end

def jwt_token(timestamp)
  payload = { account_id: account.id, timestamp: timestamp }
  JWT.encode(payload, ALERT_MGMT_CONFIG['app_secret'])
end

shared_examples 'invalid_header' do |header|
  it "with header '#{header}' responds Unauthorized" do
    request.headers['Authorization'] = header
    attributes = { name: 'TestAccountChanged', full_domain: 'FullDomainChanged' }
    put :update, params: { id: account.id, account: attributes }
    result = JSON.parse(response.body)
    expect(response.status).to eq(401)
  end
end


describe 'Authentication failure' do
  include_examples 'invalid_header', 'nil'
  include_examples 'invalid_header', 'LoremIpsum'
  include_examples 'invalid_header', 'TOKEN LoremIpsum'
  include_examples 'invalid_header',  "TOKEN #{jwt_token(Time.now.utc + 5.days)}"
end
end

我正在尝试访问 jwt_token 方法并收到此错误。

 Failure/Error: include_examples 'invalid_header',  "TOKEN #{jwt_token(Time.now.utc + 5.days)}"`jwt_token` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc).

我该如何解决这个问题?如何使其在示例组中可用?

【问题讨论】:

    标签: rspec ruby-on-rails-5 rspec-rails


    【解决方案1】:

    我不明白你为什么在你的规范文件中使用shared_exampleshared_example 在你想在不同的规范文件之间实现相同的行为时非常有用。

    我完全建议在您目前的情况下不要使用shared_example,而是使用简单的def method,如下所示:

    def authentication_fail header
      request.headers['Authorization'] = header
      attributes = { name: 'TestAccountChanged', full_domain: 'FullDomainChanged' }
      put :update, params: { id: account.id, account: attributes }
      result = JSON.parse(response.body)
      expect(response.status).to eq(401)
    end
    

    然后

    describe 'Authentication failure' do
      authentication_fail(nil)
      authentication_fail('LoremIpsum')
      authentication_fail('TOKEN LoremIpsum')
      authentication_fail( "TOKEN #{jwt_token(Time.now.utc + 5.days)}")
    end
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多