设计助手的Rspec测试 - devise_error_messages

时间:2014-03-25 13:38:27

标签: rspec ruby-on-rails-4 capybara

我有以下帮助:

def devise_error_messages!
    return "" if resource.errors.empty?

    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
    sentence = I18n.t("errors.messages.not_saved",
                      :count => resource.errors.count,
                      :resource => resource.class.model_name.human.downcase)

    html = <<-HTML
    <div id="error_explanation" class="alert alert-danger">
      <h2>#{sentence}</h2>
      <ul>#{messages}</ul>
    </div>
    </br>
    HTML

    html.html_safe
  end

我想用rspec和capybara为它写一个规范。我应该怎么开始?任何帮助将不胜感激。

提前致谢。

3 个答案:

答案 0 :(得分:1)

我自己想出来了:

require 'spec_helper'

describe DeviseHelper do
  before do
    view.stub(:resource).and_return(User.new)
    view.stub(:resource_name).and_return(:user)
    view.stub(:devise_mapping).and_return(Devise.mappings[:user])
  end

  describe "No Error Message" do
    it { helper.devise_error_messages!.should eql("") }
  end

  describe "Error Message Present" do
    it {
      view.stub(:resource).and_return(User.create)  
      helper.devise_error_messages!.should_not eql("")
    }
  end

end

答案 1 :(得分:1)

以下是使用新的rspec语法的更新:

require 'rails_helper'

RSpec.describe DeviseHelper, type: :helper do
  before do
    allow(view).to receive(:resource).and_return(User.new)
    allow(view).to receive(:resource_name).and_return(:user)
    allow(view).to receive(:devise_mapping).and_return(Devise.mappings[:user])
  end

  context 'no error messages' do
    it '#devise_error_messages!' do
      expect(helper.devise_error_messages!).to eq("")
    end
  end

  context 'with error messages' do
    it '#devise_error_messages!' do
      allow(view).to receive(:resource).and_return(User.create)
      expect(helper.devise_error_messages!).to_not eq("")
    end
  end
end

答案 2 :(得分:0)

我尝试了但是它给了我错误所以我修改了它就像这样

require 'spec_helper' 

RSpec.describe DeviseHelper, type: :helper do
  let(:resource_name) { (:contact) }
  let(:devise_mapping){ (Devise.mappings[:contact]) }

  context 'no error messages' do
    let(:resource) { (Contact.new) }
    it '#devise_error_messages!' do
      expect(devise_error_messages!).to eq("")
    end
  end

  context 'with error messages' do
    let(:resource) { (Contact.create) } 
    it '#devise_error_messages!' do
      expect(devise_error_messages!).to_not eq("")
    end
  end
end