ruby on rails 4 -设计助手的Rspec测试- design_error_messages



我有以下帮助:

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写一个规范。我该怎么开始呢?如有任何帮助,不胜感激。

我自己弄明白了:

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

以下是新的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

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

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

相关内容

  • 没有找到相关文章

最新更新