ruby-on-rails - 使用 rspec 设计和 OmniAuth twitter 集成测试

标签 ruby-on-rails rspec devise omniauth

我正在尝试编写一个集成测试,用于使用 OmniAuth 和 Devise 登录 Twitter。我在设置请求变量时遇到问题。它适用于 Controller 测试,但不适用于集成测试,这使我认为我没有正确配置规范帮助程序。我环顾四周,但似乎找不到可行的解决方案。这是我到目前为止所拥有的:

# spec/integrations/session_spec.rb
require 'spec_helper'
describe "signing in" do
  before do
    request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
    visit new_user_session_path
    click_link "Sign in with twitter"
  end

  it "should sign in the user with the authentication" do
    (1+1).should == 3
  end
end

该规范在进行测试之前就出现了错误,我不太确定 request 在哪里。变量需要初始化。错误是:
Failure/Error: request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
  NoMethodError:
    undefined method `env' for nil:NilClass

现在我使用 request我的 Controller 规范中的变量和测试通过,但它没有为集成测试初始化​​。
 # spec/spec_helper.rb
 Dir[Rails.root.join("spec/support/*.rb")].each {|f| require f}
 ...

 # spec/support/devise.rb
 RSpec.configure do |config|
   config.include Devise::TestHelpers, :type => :controller
 end

谢谢您的帮助!

最佳答案

Capybara README说“从测试中访问 session 和请求是不可能的”,所以我放弃了在测试中配置并决定在 application_controller.rb 中编写一个辅助方法.

before_filter :set_request_env
def set_request_env
  if ENV["RAILS_ENV"] == 'test'
    request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter] 
  end
end

关于ruby-on-rails - 使用 rspec 设计和 OmniAuth twitter 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378613/

相关文章:

ruby - Sublime Text 3 和 Rspec,构建错误

authentication - 如何为两个设计模型使用不同的 authentication_keys?

ruby-on-rails - 使用旧版本的 bundler

ruby-on-rails - 使用 Rails 和 Rspec,如何测试数据库未被方法触及

ruby-on-rails - 在 Rails 中编译资源时出现段错误

ruby - 我可以在中间停止 RSpec 测试运行吗?

ruby-on-rails - rspec/cucumber 运行后在哪里清理 cloudinary 文件上传

ruby-on-rails - Ruby on Rails - 简单的表单不显示单选选择的错误。其他错误显示正常

ruby-on-rails - 将设计身份验证合并到现有的用户结构中?

ruby-on-rails - Rails - group_by