Mind Dump, Tech And Life Blog
written by Ivan Alenko
published under license CC4-BY
posted at 24. Apr '24

Howto Define Method or Variable in View Spec

If you have more complicated logic in views, it may be useful to make a test since they are much faster than system specs.

This example fakes (Pundit) policy method:

RSpec.describe 'my/article', type: :view do
  before(:each) do
    def view.policy(param)
      Class.new do
        def self.whatever?; true; end
      end
    end

    render
  end

  it 'renders whatever section' do
    expect(view).to have_css('h2', text: 'whatever section')
  ...
end

Variables are set more easily, through assign:

RSpec.describe 'my/article', type: :view do
  before(:each) do
    assign(:comments, [build(:comment, body: 'Great content')])

    render
  end

  it 'renders whatever section' do
    expect(view).to have_css('h2', text: 'whatever section')
  ...
end

Now it should work just fine.

Add Comment