[英]How to make Rails submit a URL to the web for testing?
我正在為Rails 4應用編寫一段測試代碼,我想知道是否有一種方法可以使其自動化,以便每次運行時都向Web提交URL。
在瀏覽器搜索欄中鍵入特定的URL( http://website.com/add?application=Test&...&severity=ERROR )會用某些數據填充我的數據庫,我想測試一下更改URL參數是否會產生正確的結果。 有沒有辦法讓我的測試代碼自己執行此操作?
您需要2顆寶石:
將進行一些配置以啟用這些功能。 由於您是實習生,所以給您最少的樣本。
在以下步驟中,路徑/
指向Rails應用程序的根目錄,而不是文件系統的根目錄。
在/Gemfile
,添加以下行:
group :test do
gem 'rspec-rails'
gem 'faker'
end
然后運行bundle install
。
在安裝了gem之后,運行rails generate rspec:install
,它會生成文件夾/spec/
和其中的一些文件。
最后,您可以編寫測試。
運行rails generate rspec:request add
,它將在/spec/requests/adds_spec.rb
處提供一個測試腳本文件。 看起來像
require 'rails_helper'
RSpec.describe "Adds", type: :request do
describe "GET /adds" do
it "works! (now write some real specs)" do
get adds_path
expect(response).to have_http_status(200)
end
end
end
現在修改它
require 'rails_helper'
RSpec.describe "Add", type: :request do
let(:application) {Faker::Lorem.word}
let(:severity) {%w(trace debug info error fatal).sample}
# other params ...
describe "GET /add" do
it "creates some record" do
get add_path(application: application, severity: severity)
my_model = MyModel.last!
expect(my_model.application).to == application
# other expectations ...
end
end
end
然后使用bundle exec rspec spec
運行它。
PS:您可能需要在每次測試后使用database_cleaner清理數據庫。 您可能還需要factory_girl_rails來幫助您創建固定裝置。 您可能需要水豚模仿使用瀏覽器的人類。 您可能...因此,您自己找到了一本有關Rails的教科書。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.