Search code examples
ruby-on-railsrubytestingrspecrspec-rails

Why do I get "undefined method `visit'"?


I'm trying to test my app controller with RSpec on Ruby on Rails. I'm not using Capybara (since many use it). This is my spec test:

require 'spec_helper'

describe UserController do

it "create new user" do
    get :create, :user => { :email => '[email protected]', :name => 'userexample' }
    flash[:notice] = 'new user was successfully created.'
end
  describe "signup" do

  before { visit new_user_registration_path }

  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=> "[email protected]"
    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
end

Here is my Usercontroller:

class UserController < ApplicationController
def index

end

def new
     @user = User.new
end

def create
    @user = User.new(params[:user])
    if @user.save
        redirect_to user_session_path
    else
    redirect_to new_user_session_path
end

end

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

When I tested it, I got the error: undefined method 'visit':

Failure/Error: before { visit new_user_registration_path }
 NoMethodError:
   undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_2:0x132cefbc0>
 # ./spec/controllers/user_controller_spec.rb:11

Solution

  • You must to use Capybara for this function. I think your tests are not in the right place. You must to do requests specs for that. It's not for controllers specs. See the doc : https://github.com/rspec/rspec-rails/.