针对iframe内容的Rspec测试

时间:2012-11-06 10:54:59

标签: ruby-on-rails rspec ruby-on-rails-3.2 capybara

我如何为iframe内容编写rspec测试?我的iframe看起来像

<iframe src="/any url" name="Original">
   ...
   <div>test </div>
</iframe>
在iframe之间无论什么内容,我都想为那个内容写rspec测试用例。我该怎么办?

如何使用rspec检查iframe中的“test”?我写下面但没有通过

page.should have_content("test")

错误,如

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

我使用capybara - 1.1.2和rspec - 2.11.0以及rails 3.2.8

3 个答案:

答案 0 :(得分:6)

以下一个使用selenium驱动程序,可能还有其他驱动程序,但不适用于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 :(得分:2)

In my case, I needed to inspect an iframe that did not have name nor id. eg

html

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

rspec

expect(page).to have_content "From email@test.html"

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

so I could not find the iframe in any way, until I found this example in capybara entrails. Capybara source code

With that I got this solution:

expect(page).to have_content "From email@test.html"

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

答案 2 :(得分:2)

上面的答案很棒,不过我还想用以下内容扩展它们:

如果您只是断言某个页面中存在某些文本,并且想要在任何现有的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中找到给定的文本。 我相信代码非常清晰易懂,但如果您有任何问题,请告诉我。