2012-11-06 43 views
5

如何爲iframe內容編寫rspec測試?我的Iframe看起來像針對iframe內容的Rspec測試

<iframe src="/any url" name="Original"> 
    ... 
    <div>test </div> 
</iframe> 

iframe之間的任何內容,我想爲該內容寫rspec測試用例。我能怎麼做 ?

我該如何檢查「test」是否在使用rspec的iframe中?我下面寫,但沒有通過

page.should have_content("test") 

錯誤,如

Failure/Error: page.should have_content("test") 
     expected there to be content "test" in "Customize .... 

我用的水豚 - 1.1.2和RSpec - 2.11.0和軌道3.2.8

+0

根據[這個答案](http://stackoverflow.com/questions/6890364/capybarawebkit-unable-to-find-iframe-or-its-content)你需要等待iframe加載。如果你在測試'have_content'之前睡了幾秒鐘,會發生什麼? –

+1

@shioyama - 'should have_content'已經等待(默認2秒)。 – skalee

+0

@skalee哦,不知道。有趣。 –

回答

5

繼一期工程有硒驅動程序,也可能與其他驅動程序,但不適用於rack_test。

/index.html:

<!DOCTYPE html> 
<html> 
    <body> 
    <h1>Header</h1> 
    <iframe src="/iframer" id='ident' name='pretty_name'></iframe> 
    </body> 
</html> 

/iframer.html:

<!DOCTYPE html> 
<html> 
    <body> 
    <h3>Inner Header</h3> 
    </body> 
</html> 

規格:

visit "/" 
page.should have_selector 'h1' 
page.should have_selector 'iframe' 

page.within_frame 'ident' do 
    page.should have_selector 'h3' 
    page.should have_no_selector 'h1' 
end 

page.within_frame 'pretty_name' do 
    page.should have_selector 'h3' 
    page.should have_no_selector 'h1' 
end 
1

就我而言,我需要檢查的iframe未有名字或身份證。例如

HTML

<iframe class="body" src='messages/1.html'>...</iframe> 

rspec的

expect(page).to have_content "From [email protected]" 

within_frame '.body' do 
    expect(page).have_content 'You can confirm your account email through the link below:' 
end 

所以我找不到任何方式的iframe,直到我發現了水豚內臟這個例子。 Capybara source code

有了,我得到了這個解決方案:

expect(page).to have_content "From [email protected]" 

within_frame find('iframe.body') do 
    expect(page).have_content 'You can confirm your account email through the link below:' 
end 
0

從上面的答案是偉大的,但我仍然希望將它們與下面的擴展:

如果你只是想斷言一定文本存在於一個頁面中,並且想要自動檢查任何目前的iframe內部,然後我做了這個通用代碼來完成該操作:

Then (/^I should see the text "(.*?)" in less than "(.*?)" seconds$/) do |text,time| 
    result = false 
    Capybara.default_wait_time = 5 
    time_start = Time.now 
    begin 
     time_running = Time.now - time_start #Calculate how much time have been checking 
     result = page.has_text?(text) 
     unless result #If not found in normal DOM, look inside iframes 
      if page.has_css?("iframe") #Check inside iframes if present 
       (page.all(:css,"iframe")).each do |element| #If multiple iframes found, check on each of them 
        within_frame(element) do 
         result = page.has_text?(text) 
         break if result #Stop searching if text is found 
        end 
       end 
      end 
     end 
    end until (time_running.to_i >= time.to_i) || (result == true) 
    expect(result).to be true 
end 

請注意,它會一直檢查頁面,直到啓動的計時器滿足給定的秒數,或者直到在頁面或iframe中找到給定文本。 我相信這段代碼非常清晰易懂,但如果您有任何問題,請告訴我。