使用文本变量填充文本字段,如何?

时间:2019-06-03 22:00:20

标签: ruby selenium-webdriver capybara

我正在尝试使用变量填充文本字段。可以用水豚来做到这一点吗?编辑:现在也有代码和失败,对不起。

  describe 'test' do

it 'test0' do
    visit 'https://www.submarino.com.br/'

    livro = page.first('img[alt~="Livro"]').click

    nome = page.find('#product-name-default').text
    puts nome

    autor = find('table tbody tr', text: 'Autor').text
    puts autor

    isbn = find('table tbody tr', text: 'ISBN-13').text
    puts isbn

end

it 'teste1' do 
    visit 'https://www.americanas.com.br/'

    fill_in 'h_search-input',   with: isbn  **# <- here is the error**
    click_button 'h_search-btn'

end

it 'teste2' do 
    visit 'https://www.amazon.com.br/'
end
end

HTML元素

<input id="h_search-input" class="src-input" type="text" name="conteudo" placeholder="tem tuuudo, pode procurar :)" autocomplete="off" tabindex="2" value="">

失败获取:

Failures:

1) teste teste1
 Failure/Error: fill_in 'h_search-input',   with: isbn

 NameError:
   undefined local variable or method `isbn' for #<RSpec::ExampleGroups::Teste "teste1" (./spec/teste_spec.rb:23)>
 # ./spec/teste_spec.rb:27:in `block (2 levels) in <top (required)>'

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

测试是相互隔离的,也是独立的方法。您不能在一种方法中分配局部变量,而在另一种方法中访问局部变量,因为它们的作用域不同-https://www.sitepoint.com/understanding-scope-in-ruby/。但是,您可以从before块访问实例变量(因为它们是在测试实例上分配的)。您需要在使用它的测试块中获取该值,或者如果要在多个测试中使用该值,则可以使用before(:each)before(:all),具体取决于您是为每个测试还是为每个计算得出一次(通常一次不是一个好主意,因为如果在测试中更改值,则可能导致测试耦合)

describe 'test' do
  before(:each) do
    visit 'https://www.submarino.com.br/'

    livro = page.first('img[alt~="Livro"]').click

    nome = page.find('#product-name-default').text
    puts nome

    autor = find('table tbody tr', text: 'Autor').text
    puts autor

    @isbn = find('table tbody tr', text: 'ISBN-13').text
    puts @isbn
  end

  it 'teste1' do 
    visit 'https://www.americanas.com.br/'

    fill_in 'h_search-input',   with: @isbn
    click_button 'h_search-btn'
    # Add whatever expectation you are testing for here
  end

  it 'teste2' do 
    visit 'https://www.amazon.com.br/'

    ... # do something using @isbn
  end
end