4
votes

I would like to test my registration view with rspec.

I have tried many things like suggested here Testing devise views with rspec or Testing Views that use Devise with RSpec

But nothing seems to be ok, I always get an error like:

undefined local variable or method `resource'

or

does not implement: resource

My current spec (spec/views/devise/registrations/new.slim_spec.rb):

require 'rails_helper'

RSpec.describe 'devise/registrations/new.slim', type: :view do

  describe 'sign up form' do

    before do
      allow(view).to receive(:resource).and_return(User.new)
      allow(view).to receive(:resource_name).and_return(:user)
    end

    it 'does not contains an area for user avatar' do
      render
      expect(rendered).to_not include('Profile Pic')
    end
  end
end 

my environment:

  • rails 4.2.3
  • devise 3.5.1
  • rspec 3.3.0

What am I doing wrong? Thanks for your help.

Edit:

I move my code to controller spec and it works, not perfect but...

RSpec.describe Users::RegistrationsController, type: :controller do
  before(:each) do
    request.env['devise.mapping'] = Devise.mappings[:user]
  end

  describe '#new' do
    render_views

    it 'does not contains an area for user avatar' do
      get :new
      expect(response.body).to_not include('Profile Pic')
    end
  end
end
2
You should post some code to show what you have tried. - ruby_newbie
@ruby_newbie I've just added my spec. - user3671545
the correct answer can be found here: stackoverflow.com/questions/14426746/… - AdamT

2 Answers

0
votes

1. set configuration in rails_helper.rb

RSpec.configure do |config|
  config.include Devise::Test::ControllerHelpers, type: :view
  config.include Devise::Test::ControllerHelpers, type: :controller

  # add these if you need other type of rspec.
  # config.include Devise::Test::IntegrationHelpers, type: :feature
  # config.include Devise::Test::IntegrationHelpers, type: :request
end

2. your view Rspec.

# frozen_string_literal: true
require 'rails_helper'

RSpec.describe 'rendering locals in a partial', type: :view do
  let(:user) { create(:user) }

  before :each do
    sign_in user
  end

  it "displays the widget" do
    widget = Widget.create!(:name => "slicer")

    render :partial => "widgets/widget.html.erb", :locals => {:widget => widget}

    expect(rendered).to match /slicer/
  end
  end
end