Joel B Joel B - 1 month ago 11
Ruby Question

Rspec: Selecting a radio button for Sinatra form?

I am writing test specs for a Sinatra app. How can I ask rspec to click on a radio button in my form?



<form action="/reports/new" method="POST">
<div class="form-group">
<label class="col-md-4 control-label" for="radios">Borough</label>
<div>
<label>
<input name="Brooklyn" id="borough_1" value="1" type="radio">Brooklyn</input>
</label>
<label>
<input name="Bronx" id="borough_2" value="2" type="radio">Bronx</input>
</label>
<label>
<input name="Manhattan" id="borough_3" value="3" type="radio">Manhattan</input>
</label>
<label>
<input name="Queens" id="borough_4" value="4" type="radio">Queens</input>
</label>
<label>
<input name="Staten Island" id="borough_5" value="5" type="radio">Staten Island</input>
</label>
<button value="Submit" type="submit">Submit</button>
</div>
</div>
</form>





Edit: I did check out this resource but it didn't help me: stackoverflow.com/questions/11483967/… I tried
choose('Manhattan')
. However, i keep getting this error:
Failure/Error: choose('Manhattan') Capybara::ElementNotFound: Unable to find radio button "Manhattan"


Good news is that rspec is at least looking for a radio button.



visit '/reports/new'
fill_in(:title, :with => "Ben and Jerries Ice Cream")
fill_in(:business, :with => "Starbucks")
fill_in(:location, :with => "146 Rikers Street")
fill_in(:content, :with => "Some great food")
fill_in(:date, :with => "2016-09-12")
choose('Manhattan')




Answer

choose finds things by id, name or label. From the docs:

#choose([locator], options) ⇒ Object

Find a radio button and mark it as checked. The radio button can be found via name, id or label text.

Make sure that: a) Capybara is going to 'reports/new' and b) that your page is rendering those elements as expected. For example, try going to 'reports/new' yourself and selecting that element in the console (assuming you have jQuery) with:

$('#borough_3');

Or just look for it in the source.

Comments