2013-08-13 2 views
0

웹 기반 API 용 Ruby 래퍼를 작성 중이며 각 요청에는 고유 한 트랜잭션 ID가 요청과 함께 전송되어야합니다.이전의 인스턴스 변수 증가시키기 : MiniTest의 각 절

MiniTest::Spec을 사용하여 테스트 쉘을 작성했지만 각 테스트 사이에는 트랜잭션 ID가 증가하지 않습니다.

describe "should get the expected responses from the server" do 
    before :all do 
    # random number between 1 and maxint - 100 
    @txid = 1 + SecureRandom.random_number(2 ** ([42].pack('i').size * 8 - 2) - 102) 
    @username = SecureRandom.urlsafe_base64(20).downcase 
    end 

    before :each do 
    # increment the txid 
    @txid += 1 
    puts "new txid is #{@txid}" 
    end 

    it "should blah blah" do 
    # a test that uses @txid 
    end 

    it "should blah blah blah" do 
    # a different test that uses the incremented @txid 
    end 
end 

거기에 puts 라인은 @txid 실제로 각 테스트 사이에 증가되지 않는다는 그러나 보여줍니다 다음과 같이 지루한 세부 사항을 떠날

테스트 쉘은,이다.

테스트의 본문에서 인스턴스 변수에 값을 할당해도 변수 값에 아무런 영향이 없다는 것을 보여주는 테스트가 몇 가지 더 있습니다.

예상 되나요? 이것을 처리하는 올바른 방법은 무엇입니까?

답변

1

Minitest는 실제로 RSpec에서 수행하는 before :all을 지원하지 않습니다. before do에 전달하는 유형 (예 : :all 또는 :each)은 기본 구현에서 완전히 무시됩니다.

the docs은 "유형이 무시되고 이식하기가 더 쉽습니다."라고 명시합니다.

클래스 변수를 사용할 수 있습니다 (좋지는 않지만 여기에서 요구 사항을 충족합니다). 또는, Minitest :: Unit을 사용하는 경우 사용자 정의 주자를 설정할 수있는 것처럼 보입니다. 자세한 내용은 the docs, this older answerthis gist을 확인하십시오.

+0

흥미 롭습니다. 이전에는 모든 테스트가 실행되기 전에 모든 것이 테스트되기 전에 실행되었습니다. 그건 다소 어리 석다. 그러나 포인터에 감사드립니다. –

+0

흥미롭게도 [이 게시물] (https://makandracards.com/makandra/11507-using-before-all-in-rspec-will-cause-you-lots-of-trouble-unless-you-know-what-you -are-doing)은 테스트 스위트에서'before : all'을 절대 사용하지 않는 좋은 경우입니다. –

2

Minitest는 각 테스트를 테스트 클래스의 개별 인스턴스에서 실행합니다. 이 인스턴스 변수 때문에 테스트간에 공유되지 않습니다. 테스트간에 값을 공유하려면 전역 또는 클래스 변수를 사용할 수 있습니다.

describe "should get the expected responses from the server" do 
    before do 
    # random number between 1 and maxint - 100 
    @@txid ||= SecureRandom.random_number(2 ** ([42].pack('i').size * 8 - 2) - 102) 
    @@txid += 1 # increment the txid 
    puts "new txid is #{@txid}" 

    @@username ||= SecureRandom.urlsafe_base64(20).downcase 
    end 

    it "should blah blah" do 
    # a test that uses @@txid 
    end 

    it "should blah blah blah" do 
    # a different test that uses the incremented @@txid 
    end 
end 

가능한 경우 이는 아마도 좋은 생각이 아닙니다. :)

관련 문제