我有一个Rails 4应用程序,它使用自定义的身份验证gem,根据第三方API对用户进行身份验证。该应用程序需要对网站上的大多数操作进行身份验证(访问者可以做的很少)。
我正在尝试使用VCR来记录所有集成测试的身份验证过程中发出的api请求,但我在SO上找到的所有示例和Relish文档仅涵盖了如何在“describe do”规范中使用Rspec执行此操作,如下所示:
https://www.relishapp.com/vcr/vcr/v/1-6-0/docs/test-frameworks/usage-with-rspec
因为没有客户参与这个项目,所以我使用Rspec和Capybara而不是Cucumber来编写集成测试,所以我的测试使用‘功能/场景’格式,如下所示:
feature 'posts' do
scenario 'a user can log in' do
# use vcr for api request
sign_in_user # refers to a method that handles the api call to log in a user, which is what I would like VCR to record.
expect(page).to have_content("User signed in successfully")
end
end使用文档中描述的命令:
use_vcr_cassette在“scenario”块内,返回一个错误:
Failure/Error: use_vcr_cassette
undefined local variable or method `use_vcr_cassette' for #<RSpec::ExampleGroups::Posts:0x007fb858369c38>我按照我的spec/rails_helper.rb (包含在spec/spec_helper.rb中)中的文档设置VCR ...它基本上看起来像这样:
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'support/vcr_cassettes'
c.hook_into :webmock
end显然,我将gem 'vcr‘添加到了我的Gemfile开发/测试小组中,这是控制台和binding.pry中测试中的一件事。
有人在Rspec特性中使用过VCR吗?或有任何建议,我可能会做作为变通办法?
提前感谢
发布于 2015-03-11 00:02:51
解决方案: Taryn East让我找到了解决方案,但它与任何想要继续做这件事的人发布的链接略有不同。
以下是spec/rails_helper.rb或spec/spec_helper.rb中最基本的配置:
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock
c.configure_rspec_metadata!
end使用c.configure_rspec_metadata!是Rspec处理:vcr标记所必需的。
在Rspec功能规范中:
feature 'users' do
scenario 'logged in users should be able to do stuff', :vcr do
# authenticate user or make other http request here
end
end奇怪的是,在我的测试中- VCR正在记录响应,if第一次通过,但第二次失败。我将其追溯到存储的响应与接收到的响应不同。
对于正常的请求(使用excon),如下所示:
resp = Excon.post(url, :body => data, :headers => { "Content-Type" => "application/x-www-form-urlencoded", "Authorization" => authorization_header })响应具有可访问的标头,格式如下:
resp.headers["oauth_token"]它返回一个oauth令牌。
在VCR响应中,它以不同的方式存储,并且只能通过以下方式访问:
resp.headers["Oauth-Token"]这很奇怪,但还是可行的。这可能是一个错误的录像机或一些问题与宽恕...太忙了,现在不能弄清楚,但只是提醒一下,以防其他人使用这个设置,并在使用VCR盒式磁带时通过了实时http请求的测试和失败的测试。一种快速的解决方法是更改VCR盒式磁带数据以符合代码的要求,或者修改代码以接受任一可用值。
https://stackoverflow.com/questions/28951791
复制相似问题