未定义的局部变量或方法`last_email'

时间:2013-10-01 09:19:20

标签: ruby-on-rails rspec capybara actionmailer

我正在关注#275 Railscasts of Ryan Bates,但由于last_email方法,我无法通过测试。

以下是测试: spec / requests / password_resets_spec.rb

require 'spec_helper'

subject { page }

describe "Password reset for a registered user" do

  let(:user) { FactoryGirl.create(:user) }  
  before do
    visit new_password_reset_path
    fill_in t('user.email'), with: user.email
    click_button(t('submit.reset.password'))
  end

  it { should have_selector('div.alert.alert-success', t('flash.success.reset_password.sent')) }
  expect(last_email).to have_content(user.email)
end

这里出现错误信息:

spec/requests/password_resets_spec.rb:19:in `block (2 levels) in <top (required)>': undefined local variable or method `last_email' for #<Class:0x000000063b18d8> (NameError

以下是 new_password_reset 视图:

<%= form_tag password_resets_path, :method => :post do %>
  <div class="field">
    <%= label_tag :email, t('user.email') %>
    <%= text_field_tag :email, params[:email] %>
  </div>
  <%= submit_tag t('submit.reset.password'), class: "btn btn-primary" %>
<% end %>

new_password_reset 控制器create方法:

def create 
  user = User.find_by_email(params[:email])
  user.send_password_reset if user
  flash[:success] = t('flash.success.reset_password.sent')
  redirect_to root_url
end 

就像在railscast中一样,我做了以下事情:

规格/ spec_helper.rb

require 'capybara/rspec'

RSpec.configure do |config|
  # ...
  config.include(MailerMacros)
  config.before(:each) { reset_email }
end

规格/支持/ mailer_macros.rb

module MailerMacros
  def last_email
    ActionMailer::Base.deliveries.last
  end

  def reset_email
    ActionMailer::Base.deliveries = []
  end
end

1 个答案:

答案 0 :(得分:0)

这是因为你在类级而不是在块中调用last_email方法。

您需要使用expect(last_email).to have_content(user.email)块定义it,即

it "should show alert and dispatch email to the user" do
   page.should have_selector('div.alert.alert-success', t('flash.success.reset_password.sent'))
   expect(last_email).to have_content(user.email)
end