如何使用 Capybara 检查 Simple Form 的错误信息?
How to use Capybara to check error messages from Simple Form?
我有以下测试:
scenario 'with invalid attributes' do
click_button 'Create Post'
save_and_open_page
expect(page).to have_content 'Post has not been created.'
expect(page).to have_content 'Title can\'t be blank.'
expect(page).to have_content 'Content can\'t be blank.'
end
和_form.html.erb
:
<%= simple_form_for(post) do |f| %>
# post passed to simple_form_for is @post
<%= f.input :title %>
<%= f.input :content %>
<%= f.button :submit, class: 'button' %>
<% end %>
为了获得完整的错误消息,config/initializers/simple_form_bootstrap.rb
具有以下内容:
b.use :full_error, wrap_with: { tag: 'span', class: 'help-block' }
和型号 post
.rb:
class Post < ActiveRecord::Base
validates :title, :content, presence: true
end
当我 运行 rspec
时,我得到:
expected to find text "Title can't be blank." in "Post has not been created. new post * TitleTitle can't be blank * ContentContent can't be blank"
save_and_open_page
显示:
<div class="form-group string required post_title has-error">
<label class="string required control-label" for="post_title">
<abbr title="required">*</abbr> Title
</label>
<input class="string required form-control" type="text" value="" name="post[title]" id="post_title" />
<span class="help-block">Title can't be blank</span>
</div>
为什么 Capybara 不考虑 <label>
和 <span>
之间的任何空格?
看来这只是一个小错误。您的水豚规范中有一个句号:
expect(page).to have_content `Title can\'t be blank.'
而错误消息显示句号不存在:
TitleTitle can't be blank
将其从您的规范中删除,它应该会通过 :)
我有以下测试:
scenario 'with invalid attributes' do
click_button 'Create Post'
save_and_open_page
expect(page).to have_content 'Post has not been created.'
expect(page).to have_content 'Title can\'t be blank.'
expect(page).to have_content 'Content can\'t be blank.'
end
和_form.html.erb
:
<%= simple_form_for(post) do |f| %>
# post passed to simple_form_for is @post
<%= f.input :title %>
<%= f.input :content %>
<%= f.button :submit, class: 'button' %>
<% end %>
为了获得完整的错误消息,config/initializers/simple_form_bootstrap.rb
具有以下内容:
b.use :full_error, wrap_with: { tag: 'span', class: 'help-block' }
和型号 post
.rb:
class Post < ActiveRecord::Base
validates :title, :content, presence: true
end
当我 运行 rspec
时,我得到:
expected to find text "Title can't be blank." in "Post has not been created. new post * TitleTitle can't be blank * ContentContent can't be blank"
save_and_open_page
显示:
<div class="form-group string required post_title has-error">
<label class="string required control-label" for="post_title">
<abbr title="required">*</abbr> Title
</label>
<input class="string required form-control" type="text" value="" name="post[title]" id="post_title" />
<span class="help-block">Title can't be blank</span>
</div>
为什么 Capybara 不考虑 <label>
和 <span>
之间的任何空格?
看来这只是一个小错误。您的水豚规范中有一个句号:
expect(page).to have_content `Title can\'t be blank.'
而错误消息显示句号不存在:
TitleTitle can't be blank
将其从您的规范中删除,它应该会通过 :)