programing

단일 RSpec 테스트를 실행하는 방법은 무엇입니까?

telebox 2023. 6. 1. 22:40
반응형

단일 RSpec 테스트를 실행하는 방법은 무엇입니까?

다음 파일이 있습니다.

/spec/controllers/groups_controller_spec.rb

터미널에서 어떤 명령을 사용하여 해당 사양만 실행하고 어떤 디렉토리에서 명령을 실행합니까?

내 보석 파일:

# Test ENVIRONMENT GEMS
group :development, :test do
    gem "autotest"
    gem "rspec-rails", "~> 2.4"
    gem "cucumber-rails", ">=0.3.2"
    gem "webrat", ">=0.7.2"
    gem 'factory_girl_rails'
    gem 'email_spec'
end

규격 파일:

require 'spec_helper'

describe GroupsController do
  include Devise::TestHelpers

  describe "GET yourgroups" do
    it "should be successful and return 3 items" do

      Rails.logger.info 'HAIL MARRY'

      get :yourgroups, :format => :json
      response.should be_success
      body = JSON.parse(response.body)
      body.should have(3).items # @user1 has 3 permissions to 3 groups
    end
  end
end

보통 저는 합니다:

rspec ./spec/controllers/groups_controller_spec.rb:42

에▁where디42실행할 테스트 라인을 나타냅니다.

태그를 사용할 수도 있습니다.여기 보세요.

용사를 합니다.bundle exec:

bundle exec rspec ./spec/controllers/groups_controller_spec.rb:42

레이크 포함:

rake spec SPEC=path/to/spec.rb

(신용은 이 대답에 달려 있습니다.가서 그에게 투표하세요.)

EDIT(@cirosantilli 덕분):사양 내에서 하나의 특정 시나리오를 실행하려면 설명과 일치하는 정규식 패턴을 제공해야 합니다.

rake spec SPEC=path/to/spec.rb \
          SPEC_OPTS="-e \"should be successful and return 3 items\""

하여 regex " " " " " "만할 수 .it입력한 이름과 일치하는 블록입니다.

spec path/to/my_spec.rb -e "should be the correct answer"

2019 업데이트: Rspec2가 'spec' 명령에서 'rspec' 명령으로 전환되었습니다.

여러 가지 옵션이 있습니다.

rspec spec                           # All specs
rspec spec/models                    # All specs in the models directory
rspec spec/models/a_model_spec.rb    # All specs in the some_model model spec
rspec spec/models/a_model_spec.rb:nn # Run the spec that includes line 'nn'
rspec -e"text from a test"           # Runs specs that match the text
rspec spec --tag focus               # Runs specs that have :focus => true
rspec spec --tag focus:special       # Run specs that have :focus => special
rspec spec --tag focus ~skip         # Run tests except those with :focus => true

특정 테스트를 실행하기 위해 선호하는 방법이 약간 다릅니다. - 라인을 추가했습니다.

  RSpec.configure do |config|
    config.filter_run :focus => true
    config.run_all_when_everything_filtered = true
  end

내 spec_helper 파일로.

이제 특정 테스트(또는 컨텍스트 또는 사양)를 실행할 때마다 "초점" 태그를 여기에 추가하고 정상적으로 테스트를 실행할 수 있습니다. 초점 테스트만 실행됩니다.태그를 다하면, ,면▁if,▁the하제거▁the▁all.run_all_when_everything_filtered모든 테스트를 시작하고 정상적으로 실행합니다.

실행할 테스트에 사용할 파일을 편집해야 하기 때문에 명령줄 옵션만큼 빠르고 쉬운 작업이 아닙니다.하지만 훨씬 더 많은 통제력을 갖게 해주는 것 같아요.

실행. 이 을 사용자의 에 추가할 수 . 이제 이 구성을 사용자에게 추가할 수 있습니다.spec_helper.rb:

RSpec.configure do |config|
  config.filter_run_when_matching :focus
end

에 태그를 합니다.it,context또는describe해당 블록만 실행하려면:

it 'runs a test', :focus do
  ...test code
end

RSpec 설명서:

https://www.rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#filter_run_when_matching-instance_method

@답변은 이것을 해결하는 깔끔한 방법입니다.그러나 이제 Rspec 3.3에 새로운 방법이 있습니다.간단히 실행할 수 있습니다.rspec spec/unit/baseball_spec.rb[#context:#it]라인 번호를 사용하는 대신.여기서 찍은 사진:

Rspec 3.3은 예제를 식별하는 새로운 방법을 도입했습니다[...].

예를 들어, 다음 명령은 다음과 같습니다.

$ rspec spec/unit/baseball_spec.rb[1:2,1:4]…spec/unit/sec_spec.dll에 정의된 첫 번째 최상위 그룹에 정의된 두 번째 및 네 번째 예제 또는 그룹을 실행합니다.

ㅠㅠㅠㅠㅠㅠㅠㅜㅜㅜㅜㅜㅜㅜㅜㅜㅠrspec spec/unit/baseball_spec.rb:42의 시험)이 첫 시험인 , 는 간단하게 (42행의 시험)을 할 수 .rspec spec/unit/baseball_spec.rb[1:1]또는rspec spec/unit/baseball_spec.rb[1:1:1]테스트 사례가 내포된 정도에 따라 달라집니다.

프로젝트의 루트 디렉터리에서 명령을 실행합니다.

# run all specs in the project's spec folder
bundle exec rspec 

# run specs nested under a directory, like controllers
bundle exec rspec spec/controllers

# run a single test file
bundle exec rspec spec/controllers/groups_controller_spec.rb

# run a test or subset of tests within a file
# e.g., if the 'it', 'describe', or 'context' block you wish to test
# starts at line 45, run:
bundle exec rspec spec/controllers/groups_controller_spec.rb:45

또한 다음을 사용할 수 있습니다.--example(-e) 지정된 테스트 경로에 대해 'it', 'sigma' 또는 'sigma' 블록의 텍스트 레이블을 부분적으로 또는 완전히 일치시키는 특정 테스트를 실행하는 옵션:

# run groups controller specs in blocks with a label containing 'spaghetti flag is false'
bundle exec rspec spec/controllers/groups_controller_spec.rb -e 'spaghetti flag is false'

# Less granularly, you can run specs for blocks containing a substring of text 
# that matches one or more block labels, like 'spaghetti' or 'paghett'
bundle exec rspec spec/controllers/groups_controller_spec.rb -e spaghetti

예제 옵션에서 받은 문자열 인수와 일치하는 레이블을 사용하여 블록 내부에 내포된 모든 테스트를 실행합니다.

예제 옵션을 사용할 때도 추가할 것을 권장합니다.--format documentation(표시 및:-f documentation) bundle 명령(예:bundle exec rspec spec/some_file.rb -e spaghetti -f documentation). 문서 형식이 일반 형식을 대체합니다../F실행 중인 예제에 대한 중첩 블록 레이블을 보여주는 읽기 쉬운 인쇄된 내역과 함께 출력하고 각 예제에 대한 인쇄된 레이블을 출력합니다.itblock)은 통과 또는 실패 여부를 나타내는 녹색 또는 빨간색으로 표시됩니다.이렇게 하면 예제 인수가 실행하려는 규격과 일치하는지 더 잘 확인할 수 있으며 예제 인수가 많은 블럭 레이블과 일치하거나 일치된 블럭에 내포된 예제가 포함되어 있는 더 긴 테스트 실행 중에 통과/실패하는 예제를 실시간으로 볼 수 있습니다.

추가 판독치(문서 링크)

규격 파일의 단일 예제의 경우 마지막에 줄 번호를 추가해야 합니다. 예:

rspec spec/controllers/api/v1/card_list_controller_spec.rb:35

단일 파일의 경우 파일 경로를 지정할 수 있습니다. 예:

rspec spec/controllers/api/v1/card_list_controller_spec.rb

사양 폴더의 전체 Rspec 예제의 경우 이 명령을 사용하여 시도할 수 있습니다.

bundle exec rspec spec

모델의 경우 5번 라인에서만 케이스를 실행합니다.

bundle exec rspec spec/models/user_spec.rb:5

컨트롤러의 경우: 5번 라인에서만 케이스를 실행합니다.

bundle exec rspec spec/controllers/users_controller_spec.rb:5

신호 모델 또는 컨트롤러의 경우 위에서 라인 번호 제거

모든 모델에서 사례 실행

bundle exec rspec spec/models

모든 컨트롤러에서 대/소문자를 실행하려면 다음과 같이 하십시오.

bundle exec rspec spec/controllers

모든 사례 실행

 bundle exec rspec 

레일 5에서,

이 방법을 사용하여 단일 테스트 파일(한 파일의 모든 테스트)을 실행했습니다.

rails test -n /TopicsControllerTest/ -v

클래스 이름을 사용하여 원하는 파일과 일치시킬 수 있습니다.TopicsControllerTest

우리반class TopicsControllerTest < ActionDispatch::IntegrationTest

출력:

여기에 이미지 설명 입력

원하는 경우 단일 테스트 방법에 일치하도록 정규식을 조정할 수 있습니다.\TopicsControllerTest#test_Should_delete\

rails test -n /TopicsControllerTest#test_Should_delete/ -v

사용할 수 있습니다.

 rspec spec/controllers/groups_controller_spec.rb:<line_number>

라인 번호는 해당 특정 블록에 있는 테스트를 실행할 수 있도록 'timeout' 또는 'it' 라인의 라인 번호여야 합니다.대신 line_number 옆에 있는 모든 행을 실행합니다.

또한 사용자 지정 이름으로 블록을 만든 다음 해당 블록만 실행할 수 있습니다.

rspec 2부터 다음을 사용할 수 있습니다.

# in spec/spec_helper.rb
RSpec.configure do |config|
  config.filter_run :focus => true
  config.run_all_when_everything_filtered = true
end

# in spec/any_spec.rb
describe "something" do
  it "does something", :focus => true do
    # ....
  end
end

rspec 2가 있는 레일 3 프로젝트에 있는 경우 레일 루트 디렉토리에서:

  bundle exec rspec spec/controllers/groups_controller_spec.rb 

확실히 작동해야 합니다. 저는 그것을 입력하는 것에 싫증이 나서 'bersp'로 단축하기 위해 별칭을 만들었습니다.

'gem exec'은 gem 파일에 지정된 정확한 gem 환경을 로드하는 것입니다. http://gembundler.com/

Rspec2는 'spec' 명령에서 'rspec' 명령으로 전환되었습니다.

이 가드 보석을 사용하여 테스트를 자동 실행합니다.테스트 파일에서 생성 또는 업데이트 작업 후 테스트를 실행합니다.

https://github.com/guard/guard-test

또는 일반적으로 다음 명령을 사용하여 실행할 수 있습니다.

rspec 사양/컨트롤러/groups_controller_spec.message

다음과 같은 작업을 수행할 수 있습니다.

 rspec/spec/features/controller/spec_file_name.rb
 rspec/spec/features/controller_name.rb         #run all the specs in this controller

언급URL : https://stackoverflow.com/questions/6116668/how-to-run-a-single-rspec-test

반응형