Rspec错误:预计至少有1个元素匹配“form [action =”/ clients / 1“] [method =”post“]”,找到0

时间:2017-02-09 07:38:21

标签: ruby-on-rails ruby rspec minitest

Noob在这里, 让我从我做了什么以及为什么做起: 客户端和护理人员(具有不同角色的用户)使用用户模型。我做了脚手架,用--skip-migration生成客户端和看护人,然后删除了自动生成的模型(Client.rb和Caregiver.rb),并在生成的控制器和视图中将Client替换为User。

一切似乎都运转良好,但我认为这似乎只是。在我测试视图时,我收到以下错误:

 Minitest::Assertion:
       Expected at least 1 element matching "form[action="/clients/1"][method="post"]", found 0..
       Expected 0 to be >= 1.

以下是其他相关文件的内容:

控制器/ clients_controller

class ClientsController < ApplicationController

  # GET /clients/1/edit
  def edit
  end
end         

规格/视图/客户端/ edit_spec

require 'rails_helper'

RSpec.describe "clients/edit", type: :view do
  before(:each) do
      @client = FactoryGirl.create :client_user   
  end

  it "renders the edit client form" do
    render

    assert_select "form[action=?][method=?]", client_path(@client), "post" do
    end
  end
end

视图/客户端/ edit.html.haml

%h1 Editing client

= render 'form'

= link_to 'Show', @client
\|
= link_to 'Back', clients_path

视图/客户端/ _form.html.haml

= form_for @client do |f|
  - if @client.errors.any?
    #error_explanation
      %h2= "#{pluralize(@client.errors.count, "error")} prohibited this client from being saved:"
      %ul
        - @client.errors.full_messages.each do |msg|
          %li= msg

  .actions
    = f.submit 'Save'

删除现有型号时是否遗漏了任何内容?或者我该怎么办?一个型号和多个控制器。 如果需要任何其他文件?

P.S - 我没有触及过rails生成的视图。

1 个答案:

答案 0 :(得分:0)

有趣的是,你正在用rspec编写你的规范,虽然有minitest的错误,之前从未做过那种组合,但你确定你正在运行正确的测试吗?使用rspec,您应该使用bundle exec rspec

运行测试

其次,您需要将FactoryGirl创建的此对象分配给视图中的实例变量

需要'rails_helper'

describe 'clients/edit' do
  let(:client) { FactoryGirl.create(:client_user) } # Prefer using let instead of before each, why? in case you make typo in `@client` you are going to get "nil" error, if you are going to make typo in `client` you are going to get Unknown Attribute/Method error. There are more advantages to it you can read about this in rspec documentation at https://www.relishapp.com/rspec/rspec-rails/docs

  before do # before and before(:each) are basically the same
    assign(:client, client) # now you need to assign instance variable in view so those are the same when you are doing the assertion below
    render # render the view
  end

  it 'renders the edit client form' do
    render

    assert_select "form[action=?][method=?]", client_path(client), "post" do


    end

    # Rspec way
    expect(rendered).to have_css('css selector goes here')
  end
end

而且,顺便说一下,你的控制器中不需要空方法edit,rails会查找视图文件,所以如果你的文件夹中有edit。*文件,那么没有这个丑陋的空方法就可以了