Ted
Ted

Reputation: 7271

RSpec and Capybara: how to determine if a select control has a specific option selected?

Given a select control that you wish to have the applicable option selected upon form load (by obviously hydrating your model in the controller), how do you determine in an RSpec/Capybara integration test whether the proper option is actually selected?

For example, given the following select control...

<select class="select optional" id="receiving_tally_po_id" name="receiving_tally[po_id]">        
    <option value="10020">PO-10020 - Schoen Inc</option>
    <option value="10018" selected="selected">PO-10018 - Senger, Eichmann and Murphy</option>
</select>

...how would you test that selected="selected" on the value 10018?

describe "auto-populate with PO information" do
  let!(:po) { FactoryGirl.create(:po) }

  before { visit new_receiving_tally_path(:po => po) }
  # The following checks to see if the option is actually there, but not if it's selected.
  it { should have_xpath "//select[@id = '#receiving_tally_po_id']/option[@value = '#" + po.id.to_s + "' ]" }
end

UPDATE....another stab at it, but it appears to ignore the block items (it says it's all good even with erroneous info - the reason is probably obvious):

  it "should have the proper PO selected" do
    should have_selector("select#receiving_tally_po_id") do |content|
      content.should_not have_selector(:option, :value => po.id.to_s, :selected => 'selected')
    end
  end

Upvotes: 3

Views: 1498

Answers (1)

Muhamamd Awais
Muhamamd Awais

Reputation: 2385

try as follow

it " should have your_value when page loaded" do 
  find_field(field).value.should eq "your_value"
end

hope it would help

To fit the above example:

subject { page }
... 
    describe "auto-populate with PO information" do
      let!(:po) { FactoryGirl.create(:po) }
      before { visit new_receiving_tally_path(:po => po) }
      it { find_field('receiving_tally_po_id').value.should eq po.id.to_s }
    end

Upvotes: 5

Related Questions