RSPEC / Capybara没有检测到字段

时间:2014-04-24 17:33:30

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

我在使用capybara测试Rails应用时遇到问题。 我正在尝试检查是否使用特定注释创建了帖子。 问题是Capybara无法识别我的字段。

3) posts index page adding posts invalid post shows an error
     Failure/Error: click_button 'Create Post'
     Capybara::ElementNotFound:
       Unable to find button "Create Post"

4) Uploading photos displays image on post page
 Failure/Error: fill_in 'Description', with: 'My holiday pic'
 Capybara::ElementNotFound:
   Unable to find field "Description"

new.html.erb

<% if @post.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

    <ul>
    <% @post.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

<%= form_for @post, :html => { :multipart => true } do |f| %>
  <%= f.label :description %>
  <%= f.text_area :description %>

  <%= f.label :picture %>
  <%= f.file_field :picture %>

  <%= f.submit %>
<% end %>

页面来源

<p class="notice"></p>
<p class="alert"></p>

<div class="container">

<form accept-charset="UTF-8" action="/posts" class="new_post" enctype="multipart/form-data" id="new_post" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="TpeVS+Z1c4x5V+TRRXuGWYP0oLYi7fIlEU8S6f1ugwg=" /></div>
  <label for="post_description">Description</label>
  <textarea id="post_description" name="post[description]">
</textarea>

  <label for="post_picture">Picture</label>
  <input id="post_picture" name="post[picture]" type="file" />

  <input name="commit" type="submit" value="Create Post" />
</form>
</div>

</body>
</html>

功能

require 'spec_helper'

describe 'posts index page' do
  context 'no posts' do
    it 'shows a message' do
      visit '/posts'
      expect(page).to have_content 'No posts yet'
    end
  end

  describe 'adding posts' do
    context 'valid post' do
      it 'is added to the posts page' do
        visit '/posts/new'
        fill_in 'Description', with: 'My holiday pic'

        expect(current_path).to eq '/posts'
        expect(page).to have_content 'My holiday pic'
      end
    end

    describe 'deleting a post' do
      it 'removes the post' do
        visit '/posts'
        click_link 'Delete'

        expect(page).not_to have_content 'My holiday pic'
      end
    end

    context 'invalid post' do
      it 'shows an error' do
        visit '/posts/new'
        click_button 'Create Post'

        expect(page).to have_content 'error'
      end
    end
  end
end

我在相关帖子中找到了一个类似的解决方案,该帖子指的是id,例如post_description中的new.html.erb,但这没有效果。

1 个答案:

答案 0 :(得分:0)

解决。 问题是因为我在应用程序中实现了用户身份验证,但没有在测试中实现,这种方法阻止了测试找到只有登录用户应该能够看到的字段。

在posts_controller.rb

def new
  authenticate_user!
  @post = Post.new
end

一旦使用Factory Girl gem实现测试用户,测试就会顺利进行。