设计视图规格

时间:2018-03-06 13:20:09

标签: ruby-on-rails rspec devise

我习惯于编写视图规范,至少检查一下:

expect(view).to receive(:title).with('Required page title here')

title是我写的用于设置页面标题的辅助方法。)现在我正在尝试为我的Devise视图编写规范,看起来像:

- title 'Lost Password'
.row
  .col-lg-6
    = form_for resource, as: resource_name, url: password_path(resource_name) do |f|
      = render 'layouts/errors', object: resource
      .form-group
        = f.label :email
        = f.text_field :email, class: 'form-control', autofocus: true
      = f.submit 'Send me the instructions', class: 'btn btn-primary'
    %hr
    = render 'devise/shared/links'
  .col-lg-6
    = render 'devise/shared/advantages'

resourceresource_name由Devise定义。

如果我在视图上运行以下规范:

require 'rails_helper'
describe 'devise/passwords/new', type: :view do
  it 'sets the page title' do
    expect(view).to receive(:title).with('Lost Password')
    render
  end
end

它说:undefined local variable or method 'resource'。我试过了:

allow(view).to receive(:resource).and_return(User.new)

然后我得到[snip, long class definition] does not implement: resource

如何使这项工作?我不想将Capybara用于像这样微不足道的事情。

1 个答案:

答案 0 :(得分:1)

您可以通过在测试助手中编写一个简单的实现来自己提供这些助手:

def resource_name
  :user
end

def resource
  @resource ||= User.new
end

def devise_mapping
  @devise_mapping ||= Devise.mappings[:user]
end