2012-03-14 3 views
4

capybara로 테스트해야하는 비동기 javascript 함수가 있습니다. 테스트에서 js: true 옵션을 사용해야하고 config.use_transactional_fixtures = false으로 설정 한 다음 database_cleaner을 던지지 만 여전히 작동하지 않는다는 것을 이해합니다.Capybara with Javascript (Rspec, Spork 및 FactoryGirl to Boot)

cart_spec은 장바구니에 항목을 추가하고 구매하는 전체 과정을 거칩니다 (따라서 매우 중첩되어 있습니다).

checkout.html.erbstripe 라이브러리를 사용하여 신용 카드를 처리합니다. 그 테스트 자바 스크립트 기능이 있습니다.

js: true 옵션을 사용하여 테스트를 실행하면 스포츠가 데이터베이스에 저장되지 않음을 나타내는 sports_url에 '장바구니에 추가'가 존재하지 않는 테스트 실패가 발생합니다.

js: true 옵션을 사용하지 않고 테스트를 실행하면 it "should warn user that cc number is invalid" do을 제외한 모든 테스트가 통과합니다. 그 위치는 자바 스크립트가 있기 때문입니다.

나는 spork을 실행 중이며 서버를 다시 시작하려고 시도했습니다.

편집

문제는 내 sports_url이 www.example.com/sports로 이동되고, 그래서 내 테스트는 www.example.com 도메인에서 실행되고 있다는 점이다. 새로운 질문을했습니다. here. sports_path으로 액세스하면 잘 작동합니다.

가 cart_spec :

require "spec_helper" 

describe "Cart" do 
    before do 
    @user = FactoryGirl.create(:user) 
    @cart = @user.carts.create! 
    end 

    describe "using stripe" do 
     before do 
     @sport = FactoryGirl.create(:sport) 
     end 

     describe "user adds sport to cart", js: true do 
     before do 
      visit sports_url 
      click_link "Add to Cart" 
     end 

     it "should be checkout page" do 
      page.should have_content("Total") 
     end 

     describe "user clicks checkout" do 
      before do 
      click_button "Checkout" 
      end 

      it "should redirect user to sign in form" do 
      page.should have_selector('h2', text: "Sign in") 
      end 

      describe "user logs on" do 
      before do 
       fill_in "Email", with: @user.email 
       fill_in "Password", with: @user.password 
       click_button "Sign in" 

      end 

      it "should be on checkout page" do 
       page.should have_selector('h2', text: "Checkout") 
      end 

      describe "user fills in form" do 
       context "with invalid cc number" do 
       before do 
        fill_in "card-number", with: 42 
        click_button "Submit Payment" 
       end 

       it "should warn user that cc number is invalid" do 
        page.should have_content("Your card number is invalid") 
       end 
       end 
      end 

      end 
     end 
     end 
    end 

    describe "GET /carts/checkout" do 
    subject { @cart } 

    it { should respond_to(:paypal_url) } 
    it { should respond_to(:apply_discount) } 

    it "paypal_url contains notification" do 
     @cart.paypal_url(root_url, payment_notifications_url).should include("&notify_url=http%3A%2F%2Fwww.example.com%2Fpayment_notifications") 
    end 

    it "paypal_url contains invoice id" do 
     @cart.paypal_url(root_url, payment_notifications_url).should match /&invoice=\d+&/ 
    end 

    it "paypal_url contains return url" do 
     @cart.paypal_url(root_url, payment_notifications_url).should include("&return=http%3A%2F%2Fwww.example.com") 
    end 
    end 

    describe "GET /carts/discount" do 
    it "should apply discount to all line items" do 
     @cart.line_items.build(:unit_price => 48) 

     @cart.apply_discount 

     @cart.line_items.each do |lineItem| 
      lineItem.unit_price.should == 9.99 
     end 
    end 
    end 

end 

가 checkout.html.erb :

<h2>Checkout</h2> 
<span class="payment-errors"></span> 
<form action="" method="POST" id="payment-form"> 
    <div class="form-row"> 
     <label>Card Number</label> 
     <input type="text" size="20" autocomplete="off" id ="card-number" class="card-number"/> 
    </div> 
    <div class="form-row"> 
     <label>CVC</label> 
     <input type="text" size="4" autocomplete="off" class="card-cvc"/> 
    </div> 
    <div class="form-row"> 
     <label>Expiration (MM/YYYY)</label> 
     <input type="text" size="2" class="card-expiry-month"/> 
     <span>/</span> 
     <input type="text" size="4" class="card-expiry-year"/> 
    </div> 
    <button type="submit" class="submit-button">Submit Payment</button> 
</form> 

<script type="text/javascript" src="https://js.stripe.com/v1/"></script> 
<script type="text/javascript"> 
    Stripe.setPublishableKey('pk_xIm00GVAKVLMWmfeR2J8GlmeHcyhL'); 

    $(document).ready(function() { 
     $("#payment-form").submit(function(event) { 
     // disable the submit button to prevent repeated clicks 
     $('.submit-button').attr("disabled", "disabled"); 

     Stripe.createToken({ 
      number: $('.card-number').val(), 
      cvc: $('.card-cvc').val(), 
      exp_month: $('.card-expiry-month').val(), 
      exp_year: $('.card-expiry-year').val() 
     }, stripeResponseHandler); 

     // prevent the form from submitting with the default action 
     return false; 
     }); 
    }); 

    function stripeResponseHandler(status, response) { 
     if (response.error) { 
      $('.submit-button').removeAttr("disabled"); 
      //show the errors on the form 
      $(".payment-errors").html(response.error.message); 
     } else { 
      var form$ = $("#payment-form"); 
      // token contains id, last4, and card type 
      var token = response['id']; 
      // insert the token into the form so it gets submitted to the server 
      form$.append("<input type='hidden' name='stripeToken' value='" + token + "'/>"); 
      // and submit 
      form$.get(0).submit(); 
     } 
    } 
</script> 

가 spec_helper :

require 'rubygems' 
require 'spork' 

Spork.prefork do 
    # Loading more in this block will cause your tests to run faster. However, 
    # if you change any configuration or code from libraries loaded here, you'll 
    # need to restart spork for it take effect. 
    # This file is copied to spec/ when you run 'rails generate rspec:install' 
    ENV["RAILS_ENV"] ||= 'test' 
    require File.expand_path("../../config/environment", __FILE__) 
    require 'rspec/rails' 
    require 'rspec/autorun' 

    # Requires supporting ruby files with custom matchers and macros, etc, 
    # in spec/support/ and its subdirectories. 
    Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} 

    RSpec.configure do |config| 
    # == Mock Framework 
    # 
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: 
    # 
    # config.mock_with :mocha 
    # config.mock_with :flexmock 
    # config.mock_with :rr 
    config.mock_with :rspec 

    # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 
    config.fixture_path = "#{::Rails.root}/spec/fixtures" 

    # 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 = false 

    # If true, the base class of anonymous controllers will be inferred 
    # automatically. This will be the default behavior in future versions of 
    # rspec-rails. 
    config.infer_base_class_for_anonymous_controllers = false 

    config.before(:suite) do 
     DatabaseCleaner.strategy = :truncation 
    end 

    config.before(:each) do 
     DatabaseCleaner.start 
    end 

    config.after(:each) do 
     DatabaseCleaner.clean 
    end 
    end 
end 

Spork.each_run do 
    # This code will be run each time you run your specs. 

end 
+0

안녕하세요, 가짜 데이터로 페이팔 accocunt으로 내 웹 사이트를 테스트하는 방법을 알고 있습니다. capybara rspec을 사용하면 내일 도와 드릴 수 있습니까? –

+0

어떤 부분에 붙어 있습니까? –

+0

답장을 보내 주셔서 감사합니다. 저는 웹 사이트에서 paypal (시험)까지 돈 거래에 매달 렸습니다. 다음 단계는 무엇입니까? 가능한 한 빨리 회신 해주십시오 ... –

답변

0

문제는 visit <route>_url입니다. 레일 테스트의 기본 도메인은 exmaple.com입니다. 따라서 브라우저는 www.example.com/sports에 액세스하려고했는데 국제 인터넷 명명위원회에서 친절하게 예약했습니다.

나는 이것을 visit <route>_path으로 변경했으며 모든 것이 훌륭하게 작동했습니다.

0

그것은 어려운 당신에게 정확하게 제공하기 위해 여기에

는 파일입니다 대답.

JS 사양을 실행하는 경우 2 개의 프로세스가 있습니다. 그리고 당신이 평행 과정에서 페이지를 방문했을 때 기록이 저장되지 않을 수도 있습니다.

  1. @sport가 DB에 저장 될 때까지 기다려보십시오.

    click_link "Add to Cart"

    전에

wait_until { page.has_content? "Add to Cart" }

추가 카피 바라가이 말 (2 초 최대) 기다립니다. 기본 대기 시간을 늘리려면 Capybara.default_wait_time = 5을 spec_helper에 추가하십시오.

  1. DatabaseCleaner 전략이 실제로 :truncation인지 확인하십시오. 나는 네 spec_helper를 본다.그냥 두 번 확인해보세요.