Rspec - 无法找到字段"名称",无法找到按钮"创建我的帐户"

时间:2014-05-08 19:11:46

标签: ruby-on-rails rspec

我在我创建的一些测试中运行了rspec,这是我收到的输出。

Failures:

  1) User pages signup with valid information should create a user
     Failure/Error: fill_in "Name", with: "Example User"
     Capybara::ElementNotFound:
       Unable to find field "Name"
     # ./spec/requests/user_pages_spec.rb:18:in `block (4 levels) in <top (required)>'

  2) User pages signup with invalid information should not create a user
     Failure/Error: expect { click_button submit }.not_to change(User, :count)
     Capybara::ElementNotFound:
       Unable to find button "Create my account"
 # ./spec/requests/user_pages_spec.rb:12:in `block (5 levels) in <top (required)>'
 # ./spec/requests/user_pages_spec.rb:12:in `block (4 levels) in <top (required)>'

这是我的user_pages_spec.rb的rspec代码

require 'spec_helper'

describe "User pages" do
  subject { page }

  describe "signup" do
    let(:submit) { "Create my account" }

    describe "with invalid information" do
      it "should not create a user" do
        expect { click_button submit }.not_to change(User, :count)
      end
    end

    describe "with valid information" do
      before do
        fill_in "Name", with: "Example User"
        fill_in "Email", with: "user@example.com"
        fill_in "Password", with: "foobar"
        fill_in "Confirmation", with: "foobar"
      end

      it "should create a user" do
        expect { click_button submit }.to change(User, :count).by(1)
      end
    end
  end

  describe "profile page" do
    let(:user) { FactoryGirl.create(:user) }
    before { visit user_path(user) }

    it { should have_content(user.name) }
    it { should have_title(user.name) }
  end

  describe "signup page" do
    before { visit signup_path }

    it { should have_content('Sign up') }
    it { should have_title(full_title('Sign up')) }
  end
end

现在,向您展示我的HTML页面

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
  <div class="span6 offset3">
    <%= form_for(@user) do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :email %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.text_field :password %>

      <%= f.label :password_confirmation %>
      <%= f.text_field :password_confirmation %>

      <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
    <% end %>
  </div>
</div>

在这个例子中,显然你可以找到一个名为&#34; Name&#34;的文本字段。和一个按钮&#34;创建我的帐户&#34;。我对rspec看到错误感到困惑。

任何人都可以帮助我吗?

编辑:也许它没有用,因为我还没有在我的UsersController中定义一个create方法

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end
end

1 个答案:

答案 0 :(得分:0)

在开始尝试填写表单之前,您实际上并未访问任何页面。

在测试开始时,您需要visit语句。类似的东西:

describe "User pages" do

  subject { page }

  describe "signup" do
    before { visit new_user_path }
    ...