如何使用rspec测试设计视图

时间:2015-09-02 16:10:49

标签: ruby-on-rails rspec devise

我想用rspec测试我的注册视图。

我尝试了很多像这里建议的Testing devise views with rspecTesting Views that use Devise with RSpec

但似乎没有什么可以,我总是得到一个错误:

undefined local variable or method `resource'

does not implement: resource

我当前的规范(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 

我的环境:

  • rails 4.2.3
  • 设计3.5.1
  • rspec 3.3.0

我做错了什么?谢谢你的帮助。

编辑:

我将我的代码移动到控制器规范并且它有效,但不完美但是......

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 个答案:

答案 0 :(得分:0)

查看Capybara宝石。这是一个很好的指南,可以帮助您入门(https://github.com/eliotsykes/rspec-rails-examples#capybara-examples)。

他也设计了一些例子,(https://github.com/eliotsykes/rspec-rails-examples/blob/master/spec/features/user_registers_spec.rb)。

答案 1 :(得分:0)

1。在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。您的视图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