Ich habe devise eingeführt, aber ich kann den ersten Test nicht schreiben ...! Ich hatte nicht alle Informationen darüber, wie man es schreibt, also habe ich versucht, es selbst zusammenzufassen. Für Anfänger, die ihre eigenen Apps erstellt haben.
Ruby '2.6.6' Rails '5.2.4'
Gemfile
group :development, :test do
・
・
gem "rspec-rails"
gem "factory_bot_rails"
end
Zum Gemfile
Terminal
bundle install
Terminal
bundle install
Fetching gem metadata from https://rubygems.org/.............
Fetching gem metadata from https://rubygems.org/.
・
・
Using duktape 2.3.0.0
Fetching factory_bot 6.1.0
Installing factory_bot 6.1.0
Fetching factory_bot_rails 6.1.0
Installing factory_bot_rails 6.1.0
Using jbuilder 2.10.0
・
・
Using web-console 3.7.0
Bundle complete! 22 Gemfile dependencies, 95 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
Laden Sie RSpec herunter
Terminal
$ bundle exec rails generate rspec:install
Schreiben Sie Folgendes in .rspec.
rspec
--require spec_helper
--format documentation #Hier hinzufügen
Die obige Beschreibung kann vorhanden sein oder nicht, aber die Anzeige zum Zeitpunkt der Testausführung ändert sich mit oder ohne sie so stark.
Keiner
$ ...............................
Ja $ User $ #create $ is valid $ is invalid without email $ is invalid without password
Quelle: Anmelden, um in einer rspec-Testumgebung [Rails] zu entwickeln
https://qiita.com/Kohei_Kishimoto0214/items/e29e509b12a6eb484a42
### Ich habe nichts geschrieben, aber ich werde es versuchen
Der zu testende Befehl lautet
`bundle exec rspec`
Alternativ kann es individuell angegeben werden
#### **`Terminal`**
```ruby
bundle exec rspec
No examples found.
Finished in 0.00101 seconds (files took 3.71 seconds to load)
0 examples, 0 failures
Ich habe noch nicht beschrieben, was überprüft werden soll, aber es wird angezeigt ...! !! !!
Fügen Sie dem Konfigurationsteil in rails_helper.rb
die folgende Beschreibung hinzu.
spec/rails_helper.rb
RSpec.configure do |config|
config.includeFactoryBot::Syntax::Methods
end
Ich denke, es wird so aussehen.
spec/rails_helper.rb
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.include FactoryBot::Syntax::Methods
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
Als nächstes wird der folgende Satz in / spec / rails_helper.rb
auskommentiert. Bitte kommentieren Sie ihn aus.
Sie können jetzt die Datei spec / support /
laden.
/spec/rails_helper.rb
Dir[Rails.root.join('spec/support/**/*.rb')].each{|f|requiref}
/spec/rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# 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 as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }Hier nicht kommentiert
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.include FactoryBot::Syntax::Methods
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, type: :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
Erstellen Sie einen neuen Ordner und eine neue Datei "spec \ factories \ user.rb"
Dieses Mal ist Faker nicht enthalten. Geben Sie die Daten daher manuell ein. Es gibt auch eine Möglichkeit, Seriennummern zuzuweisen, aber diesmal verwenden wir die einfachste Methode.
Da die Anfangseinstellung des Geräts keinen Namen hat, sind nur die folgenden drei Elemente erforderlich. Wenn Sie die Namensspalte hinzugefügt haben, fügen Sie das Namenselement auch zu "spec \ factories \ user.rb" hinzu.
spec\factories\user.rb
FactoryBot.define do
factory :user do
email {"[email protected]"}
password {"111111"}
password_confirmation {"111111"}
end
end
Erstellen Sie spec / support / controller_macros.rb
und fügen Sie den offiziellen Inhalt unten hinzu.
Offiziell: Gewusst wie: Testen Sie Controller mit Rails (und RSpec). https://github.com/heartcombo/devise/wiki/How-To:-Test-controllers-with-Rails-(and-RSpec)
spec/support/controller_macros.rb
module ControllerMacros
def login_admin
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:admin]
sign_in FactoryBot.create(:admin) # Using factory bot as an example
end
end
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryBot.create(:user)
user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
sign_in user
end
end
end
Schreiben Sie die folgende außerhalb von RSpec.configure von rails_helper und laden Sie Geräte und Makros.
spec/rails_helper.rb
require'devise'
requireFile.expand_path("spec/support/controller_macros.rb")
Schreiben Sie Folgendes in RSpec.configure, um den test_helper und die Makros von devise im Controller zu aktivieren.
spec/rails_helper.rb
RSpec.configure do |config|
・
・
config.include Devise::Test::ControllerHelpers, type: :controller
config.include Devise::Test::IntegrationHelpers, type: :request
config.extend ControllerMacros, :type => :controller
・
・
Wenn hinzugefügt, sieht es so aus.
spec\rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'devise'
require File.expand_path("spec/support/controller_macros.rb")
require_relative 'support/controller_macros'
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.include FactoryBot::Syntax::Methods
config.include Devise::Test::ControllerHelpers, type: :controller
config.include Devise::Test::IntegrationHelpers, type: :request
config.extend ControllerMacros, :type => :controller
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
Der erstellte Benutzer wird in let gespeichert und kann wie eine Instanzvariable verwendet werden. Lassen Sie diesen Benutzer sich dann anmelden, um mithilfe der Methode login_user zu entwickeln.
Testen Sie die Validierung des Modells. Bitte setzen Sie die Validierung im Voraus.
require 'rails_helper'
RSpec.describe User, type: :model do describe 'Benutzer Registration' do it "Name, E-Mail, Passwort und Passwort_Wenn eine Bestätigung vorliegt, können Sie sich registrieren" do user = build(:user) expect(user).to be_valid # user.valid?Bestehen Sie, wenn es wahr ist end
end
Quelle: [Test mit Rspec ① (Komponententest: Validierungstest)] (https://misukeblog.com/rspec/) Quelle: [Test mit Rspec② (Integrationstest)] (https://misukeblog.com/rspec2/)
Nach dem Schreiben
Terminal
bundle exec rspec
Hinausgehen
Sollte sein! !! !! !! Damit ist fertig! !!
Terminal
$ bundle exec rspec
User
Name, E-Mail, Passwort und Passwort_Wenn eine Bestätigung vorliegt, können Sie sich registrieren
Finished in 0.5297 seconds (files took 9.34 seconds to load)
1 example, 0 failures
Terminal
& rails g rspec:model user
conflict spec/models/user_spec.rb
Overwrite C:/Users/deeep/techpitgram/spec/models/user_spec.rb? (enter "h"
for help) [Ynaqdhm]
force spec/models/user_spec.rb for help) [Ynaqdhm]
$ bundle
Migrations are pending. To resolve this issue, run:
bin/rails db:migrate RAILS_ENV=test
No examples found.
In einem solchen Fall, wie angewiesen
Terminal
$ rails db:migrate RAILS_ENV=test
Machen wir das
Wenn Sie eine solche Fehlermeldung erhalten, handelt es sich um einen alten Edelstein, der in die Edelsteindatei eingemischt ist.
Terminal
$ bundle exec rspec
2020-09-02 22:36:39 WARN Selenium [DEPRECATION] Selenium::WebDriver::Chrom
e#driver_path= is deprecated. Use Selenium::WebDriver::Chrome::Service#dri
ver_path= instead.
An error occurred while loading ./spec/models/user_spec.rb.
Failure/Error: require File.expand_path('../config/environment', __dir__)
Selenium::WebDriver::Error::WebDriverError:
per-2.1.1/bin/chromedriver-helper"
# ./config/application.rb:7:in `<top (required)>'
# ./config/environment.rb:2:in `<top (required)>'
# ./spec/rails_helper.rb:4:in `require'
# ./spec/rails_helper.rb:4:in `<top (required)>'
# ./spec/models/user_spec.rb:1:in `require'
# ./spec/models/user_spec.rb:1:in `<top (required)>'
No examples found.
Finished in 0.00008 seconds (files took 7.23 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples
Referenz: Rspec funktioniert nicht Laden von rails_helper https://teratail.com/questions/247938?link=qa_related_pc
Schreiben Sie das Gemfile neu.
Gemfile
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of chromedriver to run system tests with Chrome
#gem 'chromedriver-helper' #Löschen Sie diesen einen Satz oder kommentieren Sie ihn aus
gem 'webdrivers', '~> 3.0' #Fügen Sie diese eine Zeile hinzu
gem 'rspec-rails'
gem "factory_bot_rails"
end
・
・
gem 'devise'
Und
Terminal
bundle install
Sie sollten dazu in der Lage sein!
Ich wäre Ihnen dankbar, wenn Sie auf Fehler hinweisen könnten.
[Verfahren zum Installieren von Rspec und Factory_bot in der Rails-App] (https://qiita.com/Ushinji/items/522ed01c9c14b680222c)
[RSpec-Anfänger entwickelt ein Authentifizierungssystem-Test] (https://qiita.com/zongxiaojie/items/d488edd42ba3864859c7)
[So melden Sie sich an, um in einer rspec-Testumgebung [Rails] zu entwickeln] (https://qiita.com/Kohei_Kishimoto0214/items/e29e509b12a6eb484a42)
[Testen des Controllers mit Gerät] (https://qiita.com/nysalor/items/ef3d658ff76bee165379)
[Hinweise zum Unit-Test mit RSpec @TECH CAMP # 11-note] (https://note.com/ruquia7/n/n00ff04fc9129)
Ruby on Rails Unit-Test des Modells mit rspec-note] (https://note.com/vixer93/n/n6ef6555d7a3e)
[Über den Fehler "bin / Rails db: migrate RAILS_ENV = test" nach der Migration in Rails] (https://teratail.com/questions/178462)
Recommended Posts