pix*_*rth 18 rspec ruby-on-rails instance-variables
如何使用rspec测试我的邮件程序中是否设置了某个实例变量?分配回来未定义..
require File.dirname(__FILE__) + '/../../spec_helper'
describe UserMailer do
it "should send the member user password to a User" do
user = FG.create :user
user.create_reset_code
mail = UserMailer.reset_notification(user).deliver
ActionMailer::Base.deliveries.size.should == 1
user.login.should be_present
assigns[:person].should == user
assigns(:person).should == user #both assigns types fail
end
end
Run Code Online (Sandbox Code Playgroud)
返回的错误是:
undefined local variable or method `assigns' for #<RSpec::Core::ExampleGroup::Nested_1:0x007fe2b88e2928>
Run Code Online (Sandbox Code Playgroud)
Pet*_*vin 22
assigns仅针对控制器规范定义,并且通过rspec-rails gem完成.在RSpec中没有测试实例变量的通用机制,但您可以使用内核instance_variable_get来访问您想要的任何实例变量.
因此,在您的情况下,如果object您想要检查其实例变量的对象,您可以编写:
expect(object.instance_variable_get(:@person)).to eql(user)
Run Code Online (Sandbox Code Playgroud)
至于获得UserMailer实例的支持,我看不出有任何办法可以做到这一点.查看https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb中的method_missing定义,每当调用未定义的类方法时,将创建一个新的邮件程序实例,其名称与实例方法.但是那个实例没有保存在我能看到的任何地方,只返回了值.这是目前在github上定义的相关代码:.message
课程方法:
def respond_to?(method, include_private = false) #:nodoc:
super || action_methods.include?(method.to_s)
end
def method_missing(method_name, *args) # :nodoc:
if respond_to?(method_name)
new(method_name, *args).message
else
super
end
end
Run Code Online (Sandbox Code Playgroud)
实例方法:
attr_internal :message
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
# will be initialized according to the named method. If not, the mailer will
# remain uninitialized (useful when you only need to invoke the "receive"
# method, for instance).
def initialize(method_name=nil, *args)
super()
@_mail_was_called = false
@_message = Mail.new
process(method_name, *args) if method_name
end
def process(method_name, *args) #:nodoc:
payload = {
mailer: self.class.name,
action: method_name
}
ActiveSupport::Notifications.instrument("process.action_mailer", payload) do
lookup_context.skip_default_locale!
super
@_message = NullMail.new unless @_mail_was_called
end
end
Run Code Online (Sandbox Code Playgroud)