天道酬勤,学无止境

Rails application's port number in a rspec test

I would like to test the json responses of a rails application using rspec in combination with faraday and faraday_middleware. To use faraday one needs the application URL. In the tests I would like to use localhost + a port number.

The question is, how can I get or set the port number of the current application instance in a rspec test environment?

There are a similar questions but no satisfying answers here and here.

Any ideas?

评论

I had the same need (Watir+RSpec), but the problem is: there is no Rack stack running by default during tests...

I found this solution:

In spec_helper.rb:

HTTP_PORT = 4000

test_instance_pid = fork do
  exec 'unicorn_rails -E test -p %d' % HTTP_PORT
end

at_exit do
  Process.kill "INT", test_instance_pid
  Process.wait
end

Which start the test stack once for all spec tests, and kill it at the end. (In this sample, I am using unicorn, but we can imagine using any other server)

In the spec, I reuse the HTTP_PORT constant to build URL:

browser.goto "http://localhost:#{HTTP_PORT}/"

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Rspec 测试 Rails 重定向中的 test.host(test.host in Rspec testing Rails redirect)
    问题 这是 Rails 3.1.12 应用程序中test.rb环境文件中的一行: config.action_mailer.default_url_options = config.action_controller.default_url_options = { :host => "127.0.0.1", :port => 3000 } 现在这是我做的测试: subject { get :success } subject.should redirect_to(:home) 这会产生一个错误: Failure/Error: subject.should redirect_to(:home) Expected response to be a redirect to <http://127.0.0.1:3000/> but was a redirect to <http://test.host/> 我做错了什么? 或者,测试主机在哪里配置? 这是 spec_helper.rb 文件以供完整参考。 # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] = 'test' require File.expand_path("../../config
  • database_cleaner 正在擦除我的开发数据库(database_cleaner is wiping my development database)
    问题 我为 rails 4 应用程序配置了database-cleaner ,每次运行测试时,我发现我的数据库在test和development环境中都被清除了。 我的配置在rails_helper如下: ENV["RAILS_ENV"] ||= 'test' # This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'database_cleaner' Rails.env = "test" # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run
  • database_cleaner is wiping my development database
    I have database-cleaner configured for my rails 4 application, Each time I run the test, I discovered that my database gets wiped out in both the test and development environment. My configurations are in rails_helper as follow: ENV["RAILS_ENV"] ||= 'test' # This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'database_cleaner' Rails.env = "test" # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files
  • Rails / Rspec使测试通过http基本认证通过(Rails/Rspec Make tests pass with http basic authentication)
    问题 这是我在应用程序控制器文件(application_controller.rb)中的http基本身份验证 before_filter :authenticate protected def authenticate authenticate_or_request_with_http_basic do |username, password| username == "username" && password == "password" end end 和我的家庭控制器的索引操作的默认测试(spec / controllers / home_controller_spec.rb) require 'spec_helper' describe HomeController do describe "GET 'index'" do it "should be successful" do get 'index' response.should be_success end end 由于身份验证方法,测试无法运行。 我可以评论“ before_filter:authenticate”来运行它们,但我想知道是否有办法使它们与该方法一起使用。 谢谢! 回答1 更新(2013):Matt Connolly提供了GIST,该GIST还可用于请求和控制器规范:http://gist
  • PG::ConnectionBad:将 rails 从 4.2 升级到 5.2 后连接关闭(PG::ConnectionBad: connection is closed after upgrading rails from 4.2 to 5.2)
    问题 我已将项目的 Rails 版本从 4.2 升级到 5.2.1,由于完整跟踪中的 pg 连接关闭错误,我的一些测试失败,如下所示。 Failure/Error: DatabaseCleaner[:active_record].clean_with(:truncation) ActiveRecord::StatementInvalid: PG::ConnectionBad: connection is closed: TRUNCATE TABLE "public"."alerts", "public"."article_attachments", "public"."article_check_specification_tolerances", "public"."article_machine_part_settings", "public"."articles", "public"."attachments", "public"."check_batches", "public"."check_groups", "public"."check_specification_machine_types", "public"."check_specification_priorities", "public"."check_specification_responsibility
  • How to connect to Postgres in GithHub Actions
    I am trying GitHub Actions for CI with a Ruby on Rails application. My setup is with VM, not running the Ruby build in a container. This is my workflow yml. It runs all the way without errors until the step "Setup Database". name: Rails CI on: push: branches: - master pull_request: branches: - master jobs: build: runs-on: ubuntu-latest services: postgres: image: postgres:10.10 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: db_test ports: - 5432/tcp options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 redis: image: redis:latest
  • PG::ConnectionBad: connection is closed after upgrading rails from 4.2 to 5.2
    I have upgraded my rails version of a project from 4.2 to 5.2.1 some of my tests are failed because of pg connection closed error on the full trace is is as following. Failure/Error: DatabaseCleaner[:active_record].clean_with(:truncation) ActiveRecord::StatementInvalid: PG::ConnectionBad: connection is closed: TRUNCATE TABLE "public"."alerts", "public"."article_attachments", "public"."article_check_specification_tolerances", "public"."article_machine_part_settings", "public"."articles", "public"."attachments", "public"."check_batches", "public"."check_groups", "public"."check_specification
  • 如何在 Rails / Capybara / Cucumber 或 Rspec 中测试帖子(How to test posts in Rails / Capybara / Cucumber or Rspec)
    问题 我正在使用 rspec、cucumber 和 capybara,我正在寻找一种方法来测试恶意用户无法破解表单然后发布到他/她没有权限的网址。 我在 cancan 中设置了我的权限,这样这“应该”起作用,但是,我可以测试它的唯一方法是自己破解表单。 我怎样才能自动化这种测试? 使用 webrat,我可以在使用 rspec 的单元测试中执行此操作,例如 put :update, :user_id => @user.id, :id => @user_achievement.id response.should contain("Error, you don't have permission to access that!") 然而,在水豚中,似乎只能访问。 我找不到办法做到这一点,我到处搜索。 任何帮助将不胜感激,谢谢 回答1 我认为你可以用rack-test https://github.com/brynary/rack-test 做到这一点 在您的 Gemfile 中: gem 'rack-test' 在你的 env.rb 文件中 module CapybaraApp def app; Capybara.app; end end World(CapybaraApp) World(Rack::Test::Methods) 某处的步骤定义: When /^I send a
  • How to test render status: 404 with Rails4 and RSpec when using rescue_from
    I have a Rails4 application with a 'PagesController'. The show-method throws a customized Exception 'PageNotFoundError' when a Page is not found. On top of the controller I defined rescue_from PageNotFoundError, with: :render_not_found render not found is a private method of PagesController and looks like: def render_not_found flash[:alert]=t(:page_does_not_exists, title: params[:id]) @pages = Page.all render :index, status: :not_found #404 end The rails-log in development-mode shows: Started GET "/pages/readmef" for 127.0.0.1 at 2013-08-02 23:11:35 +0200 Processing by PagesController#show as
  • 在 rspec 中指定内容类型(Specifying Content Type in rspec)
    问题 我正在尝试构建一个通过 POST 发送 JSON(或 XML)的 rspec 测试。 但是,我似乎无法真正让它工作: json = {.... data ....}.to_json post '/model1.json',json,{'CONTENT_TYPE'=>'application/json'} 和这个 json = {.... data ....}.to_json post '/model1.json',json,{'Content-Type'=>'application/json'} 有任何想法吗? 谢谢! 回答1 有一种方法可以在此线程中进行描述 - 这是一种 hack,但它似乎有效: @request.env["HTTP_ACCEPT"] = "application/json" json = { ... data ... }.to_json post :create, :some_param => json 回答2 在 Rails 3 中,你可以跳过标题和@request.env内容,只需在你的 post 调用中添加一个format参数,例如: post :create, format: :json, param: 'Value of Param' 回答3 很多挫折和变化,这对我有用。 Rails 3.2.12 规范 2.10 @request.env[
  • test.host in Rspec testing Rails redirect
    Here's a line from my test.rb environnment file in a Rails 3.1.12 app: config.action_mailer.default_url_options = config.action_controller.default_url_options = { :host => "127.0.0.1", :port => 3000 } Now here's the test I make: subject { get :success } subject.should redirect_to(:home) This produces an error: Failure/Error: subject.should redirect_to(:home) Expected response to be a redirect to <http://127.0.0.1:3000/> but was a redirect to <http://test.host/> What did I do wrong? Or else, where the testing host be configured? Here's the spec_helper.rb file for complete reference. # This file
  • rspec test a private method within a private method that needs to be stubbed
    Simplecov detected that I was missing some tests on my lib/api_verson.rb class: class ApiVersion def initialize(version) @version = version end def matches?(request) versioned_accept_header?(request) || version_one?(request) end private def versioned_accept_header?(request) accept = request.headers['Accept'] accept && accept[/application\/vnd\.#{Rails.application.secrets.my_app_accept_header}-v#{@version}\+json/] end def unversioned_accept_header?(request) accept = request.headers['Accept'] accept.blank? || accept[/application\/vnd\.#{Rails.application.secrets.my_app_accept_header}/].nil? end
  • Rails RSpec设置子域(Rails rspec set subdomain)
    问题 我正在使用rSpec来测试我的应用程序。 在我的应用程序控制器中,我有一个像这样的方法: def set_current_account @current_account ||= Account.find_by_subdomain(request.subdomains.first) end 是否可以在我的规范中设置request.subdomain? 也许在之前的块中? 我是rSpec的新手,因此,对此的任何建议将非常感谢。 埃夫 回答1 我想出了如何解决这个问题。 在我的规范中的before块中,我简单地添加了: before(:each) do @request.host = "#{mock_subdomain}.example.com" end 这会将request.subdomains.first设置为mock_subdomain的值。 希望有人觉得这很有用,因为它在网络上的其他地方都无法很好地解释。 回答2 我知道这是一个相对较旧的问题,但是我发现这取决于您正在运行的测试类型。 我也正在运行Rails 4和RSpec 3.2,因此我确定自从提出此问题以来,某些事情已经改变。 索取规格 before { host! "#{mock_subdomain}.example.com" } 水豚功能规格 before { Capybara.default_host =
  • 如何测试渲染状态:使用rescue_from 时使用Rails4 和RSpec 的404(How to test render status: 404 with Rails4 and RSpec when using rescue_from)
    问题 我有一个带有“PagesController”的 Rails4 应用程序。 当找不到页面时,显示方法会抛出自定义异常“PageNotFoundError”。 在控制器顶部,我定义了rescue_from PageNotFoundError, with: :render_not_found render not found是PagesController一个私有方法,看起来像: def render_not_found flash[:alert]=t(:page_does_not_exists, title: params[:id]) @pages = Page.all render :index, status: :not_found #404 end 开发模式下的 rails-log 显示: Started GET "/pages/readmef" for 127.0.0.1 at 2013-08-02 23:11:35 +0200 Processing by PagesController#show as HTML Parameters: {"id"=>"readmef"} .. Completed 404 Not Found in 14ms (Views: 12.0ms) 所以,到目前为止,我的 :status => :not_found 工作正常。 当我做curl
  • rspec 在需要存根的私有方法中测试私有方法(rspec test a private method within a private method that needs to be stubbed)
    问题 Simplecov 检测到我在lib/api_verson.rb类上缺少一些测试: class ApiVersion def initialize(version) @version = version end def matches?(request) versioned_accept_header?(request) || version_one?(request) end private def versioned_accept_header?(request) accept = request.headers['Accept'] accept && accept[/application\/vnd\.#{Rails.application.secrets.my_app_accept_header}-v#{@version}\+json/] end def unversioned_accept_header?(request) accept = request.headers['Accept'] accept.blank? || accept[/application\/vnd\.#{Rails.application.secrets.my_app_accept_header}/].nil? end def version_one?(request) @version
  • application.css not being served as an asset
    EDIT 4, 5 and 6 8 hours in, any more ideas are welcome :) Maybe this bug is already known and solved, but I get the behaviour I described in edit 2&3, when you have this in a .css.erb file in app/assets/stylesheets : li { background-image: url(<%= asset_path "logo_80px_80px.png" %>); } The problem part seems to be the asset_path method call, but .css.scss also breaks it with: li { background-image: url(image-path("logo_80px_80px.png")); } My GemFile is: source 'http://rubygems.org' gem 'rails', '3.1.3' gem 'pg', '0.11.0' gem 'gravatar_image_tag', '1.0.0.pre2' gem 'will_paginate' gem 'rake' gem
  • Capybara 的 HTTP 基本身份验证(HTTP basic auth for Capybara)
    问题 我正在为我的 Rails 3 应用程序编写一些 RSpec 测试,并尝试从 Webrat 切换到 Capybara。 到目前为止一切顺利,但该应用程序使用 HTTP 基本身份验证来授权我的管理员用户,知道如何使用 Capybara 进行测试吗? 这是我当前的 Webrat 步骤: it 'should authenticate for admin' do basic_auth('user', 'secret') visit '/admin' response.status.should eql 200 response.status.should_not eql 401 end 我如何用 Capybara 做到这一点? 谢谢! 回答1 我使用page.driver.basic_authorize(name, password)让它工作 更新: 目前,在 Capybara 升级后,我正在使用这堆解决方法: if page.driver.respond_to?(:basic_auth) page.driver.basic_auth(name, password) elsif page.driver.respond_to?(:basic_authorize) page.driver.basic_authorize(name, password) elsif page.driver
  • application.css 没有被用作资产(application.css not being served as an asset)
    问题 编辑 4、5 和 6 8 小时后,欢迎提出更多想法:) 也许这个 bug 已经知道并解决了,但是当你在 app/assets/stylesheets 的 .css.erb 文件中有这个时,我得到了我在编辑 2&3 中描述的行为: li { background-image: url(<%= asset_path "logo_80px_80px.png" %>); } 问题部分似乎是asset_path方法调用,但 .css.scss 也打破了它: li { background-image: url(image-path("logo_80px_80px.png")); } 我的 GemFile 是: source 'http://rubygems.org' gem 'rails', '3.1.3' gem 'pg', '0.11.0' gem 'gravatar_image_tag', '1.0.0.pre2' gem 'will_paginate' gem 'rake' gem 'jquery-rails' gem 'nested_form' gem 'acts-as-taggable-on' gem 'sass-rails' group :assets do gem 'coffee-rails', '~> 3.1.0' gem 'uglifier', '>= 1.0.3'
  • Ruby on Rails:/ bin / sh:rspec:找不到命令(Ruby on Rails: /bin/sh: rspec: command not found)
    问题 我目前正在阅读Michael Hartl的RoR教程,并在尝试运行Spork和Guard时陷入了第3章。 当尝试运行测试时,我得到: /bin/sh: rspec: command not found 是的,我确实到处寻找答案,但是我看不到RubyTest.sublime.settings文件在哪里,所以我不知道如何编辑它。 谁能帮我解决错误的方法? 这是我的用户fodler中的Rubytest.sublime.settings文件 { "erb_verify_command": "bundle exec erb -xT - {file_name} | ruby -c", "ruby_verify_command": "bundle exec ruby -c {file_name}", "run_ruby_unit_command": "bundle exec ruby -Itest {relative_path}", "run_single_ruby_unit_command": "bundle exec ruby -Itest {relative_path} -n '{test_name}'", "run_cucumber_command": "bundle exec cucumber {relative_path}", "run_single_cucumber
  • 运行 Rails 服务器会更改测试结果吗?(Running rails server changes test result?)
    问题 与这个问题相关,我遇到了一个奇怪的情况。 ruby on rails - 使用 RSpec/Capybara/Poltergeist 登录测试失败_ruby_帮酷编程问答 只需运行测试 bin/rspec spec/features/spec.rb 11871 spring server | myapp | started 32 secs ago 11877 spring app | myapp | started 31 secs ago | test mode 我从 PhantomJS 获取日志,例如: API.ajax:GET /user :failed httpStatus:0 error undefined 使用在开发中运行的服务器运行测试 bin/rails s然后bin/rspec spec/features/spec.rb 我从 PhantomJS 获取日志,例如: API.ajax:POST /sessions :failed httpStatus:401 error [object Object] 看起来 PhantomJS 甚至无法在没有服务器在开发中运行的情况下访问 /sessions url。 (无论如何它都失败了..) 有没有人有同样的经历? 我不知道为什么运行 dev server 会做出这个改变,希望有解决测试失败的线索。 我正在使用 RSpec