rspec控制器测试失败,模型中出现参数错误

时间:2014-04-24 07:28:22

标签: ruby-on-rails rspec callback constants

我有这个问题,我正在测试我的控制器POST方法,我收到此错误:

ArgumentError:
       Missing invite relation

我有发送的表单和回调after_save调用其他方法调用其他方法传递常量。但是被调用的方法调用验证在该常量上失败。

以下是代码片段。型号:

after_save :maintain_sender_attr

def maintain_sender_attr
    self.affiliate_receivers.each do |count|
      unless count.email == ""
        send_email(count.email)
      end
    end
  end

def send_email(to)
      @resource_invite = InviteSender::NewInvite.new(self, to, CONTENT_TYPE_INVITE)
      @resource_invite.body_html = prepare(@resource_invite.invite.body_html)
      @resource_invite.send
    end

    def prepare body_html
      context_objects.each {|key, value| body_html.gsub! "[#{key}]", value}
      body_html
    end

这是常数:

NOTIFICATION_CONTENT_TYPES = [
  CONTENT_TYPE_INVITE = 'referral_invite'
]

这里是引发错误的地方:

class InviteSender::Base
  attr_accessor :missing_fields, :body_html, :invite, :owner, :to

  # Initialize new sender instance
  # @notification [Notification, String] notification or notification content_type
  def initialize owner, to, invite
    @owner = owner
    @to = to
    if invite.is_a? Invite
      @invite = invite
    else
      @invite = Invite.find_by(content_type: invite)
    end

    validate

    load_body_html_template
  end

def validate
    raise ArgumentError, "Missing owner relation" if @owner.nil?
    raise ArgumentError, "Missing invite relation" if @invite.nil?
    raise ArgumentError, "Missing to relation" if @to.nil?
    raise NotImplementedError, "Missing #locale method" unless respond_to? :locale
  end

最后测试本身:

describe "with valid attributes" do
      it "creates new sender and there affiliated receivers" do
        expect{
          post :create, node_id: @node.id, locale: @node.locale, affiliate_sender: FactoryGirl.attributes_for(:affiliate_sender, :affiliate_receivers_attributes =>{"0"=>{"email"=>"test@test.com"}}), format: :json
        }.to change(AffiliateSender, :count).by(1)
      end

      it "it return success json" do
        post :create, node_id: @node.id, locale: @node.locale , affiliate_sender: FactoryGirl.attributes_for(:affiliate_sender, :affiliate_receivers_attributes =>{"0"=>{"email"=>"test@test.com"}}), format: :json
        response.status.should eq(200)
      end
    end

我无法发现并且究竟出了什么问题。常量在config/environment.rb上定义,但感觉常量为空,因为如果常量为空则会引发此错误!我是否必须存根或moch这个常数?

1 个答案:

答案 0 :(得分:0)

您实际上是将NOTIFICATION_CONTENT_TYPES定义为“对其内容进行评估的常量”数组。这意味着

NOTIFICATION_CONTENT_TYPES # => ["referral_invite"]

因此,要访问正确的常数,您必须这样做:

NOTIFICATION_CONTENT_TYPES[0]

最好是以简洁的方式定义它:

NOTIFICATION_CONTENT_TYPES = { content_type_invite: 'referral_invite' }

然后您可以使用

访问正确的值
NOTIFICATION_CONTENT_TYPES[:content_type_invite]