Search code examples
rspecrspec-rails

RSpec: New User view test failing, when it should be passing


I have the this test:

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

And this page, the form is in the second line of this image:

HtmlCode inspection

This test fails saying that there were no forms found.

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

What must I change in the test to make it pass?


Solution

  • The problem is that the test is describing a new action, but in the before(:each) block, A user is being created, thus triggering a edit action.

    So the problem was on the test itself, not in the view

    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