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:
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
Look into the Capybara gem. Here is a great guide to get you started ( https://github.com/eliotsykes/rspec-rails-examples#capybara-examples ).
He has devise examples as well, ( https://github.com/eliotsykes/rspec-rails-examples/blob/master/spec/features/user_registers_spec.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
# 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.