RSpec:新用户视图测试失败,何时应该通过

时间:2017-10-17 17:00:45

标签: rspec rspec-rails

我有这个测试:

require 'rails_helper'
require 'support/factory_girl'

RSpec.describe 'users/new', type: :view do
    before(:each) do
        assign(:user, create(:user))
    end

    it 'renders new user form' do
        render
        assert_select 'form[action=?][method=?]', users_path, 'post'
    end
end

在此页面中,表单位于此图像的第二行:

HtmlCode inspection

此测试未能说没有找到任何表格。

rspec spec/views/users/new.html.erb_spec.rb

users/new
  renders new user form (FAILED - 1)

Failures:

  1) users/new renders new user form
     Failure/Error: assert_select 'form[action=?][method=?]', users_path, 'post'

     Minitest::Assertion:
       Expected at least 1 element matching "form[action="/users"][method="post"]", found 0..
       Expected 0 to be >= 1.
     # /home/ramses/.rvm/gems/ruby-2.4.0@gym-app/gems/minitest-5.10.3/lib/minitest/assertions.rb:139:in `assert'
     # /home/ramses/.rvm/gems/ruby-2.4.0@gym-app/gems/minitest-5.10.3/lib/minitest/assertions.rb:270:in `assert_operator'
     # /home/ramses/.rvm/gems/ruby-2.4.0@gym-app/gems/rails-dom-testing-2.0.3/lib/rails/dom/testing/assertions/selector_assertions.rb:277:in `assert_size_match!'
     # /home/ramses/.rvm/gems/ruby-2.4.0@gym-app/gems/rails-dom-testing-2.0.3/lib/rails/dom/testing/assertions/selector_assertions.rb:172:in `block in assert_select'
     # /home/ramses/.rvm/gems/ruby-2.4.0@gym-app/gems/rails-dom-testing-2.0.3/lib/rails/dom/testing/assertions/selector_assertions.rb:171:in `tap'
     # /home/ramses/.rvm/gems/ruby-2.4.0@gym-app/gems/rails-dom-testing-2.0.3/lib/rails/dom/testing/assertions/selector_assertions.rb:171:in `assert_select'
     # ./spec/views/users/new.html.erb_spec.rb:11:in `block (2 levels) in <top (required)>'

Finished in 0.24509 seconds (files took 2.93 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/views/users/new.html.erb_spec.rb:9 # users/new renders new user form

我必须在测试中做些什么才能让它通过?

2 个答案:

答案 0 :(得分:1)

我认为渲染视图存在问题(也许你没有设置var,并且收到错误?)

这样的东西:

it 'renders new user form' do
    render
    puts subject
    assert_select 'form[action=?][method=?]', users_path, 'post'
end

检查那里有什么。

您可以在那里设置断点,而不是puts subject,并在那里检查subject的内容,或将其保存在html文件中,然后在浏览器中打开以供检查。

答案 1 :(得分:1)

问题是该测试正在描述new操作,但在before(:each)块中,正在创建用户,从而触发edit操作。

所以问题出在测试本身,而不是在视图中

require 'rails_helper'
require 'support/factory_girl'

RSpec.describe 'users/new', type: :view do
    before(:each) do
        #use build instead of create, to pass a non-saved user
        assign(:user, build(:user))
    end

    it 'renders new user form' do
        render
        # you can use byebug to inspect variables.
        # byebug
        # I figured this out by inspecting the contents of the rendered var
        #inside byebug, use var to show all variables in context
        assert_select 'form[action=?][method=?]', users_path, 'post'
    end
end