RubyonRails——如何在rspec测试中访问示例变量

mf98qq94  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(338)

如何访问 pic 在我的rspec测试中?我不断得到以下错误:

F

Failures:

  1) TrelloToAc::Card#pic return pic url from trello card
     Failure/Error: expect(result).to be_a String
       expected :pic to be a kind of String
     # ./spec/services/trello_to_ac/card_spec.rb:17:in `block (3 levels) in <top (required)>'

Finished in 1.97 seconds (files took 13.5 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/services/trello_to_ac/card_spec.rb:14 # TrelloToAc::Card#pic return pic url from trello card

这似乎需要时间 pic 字面上,就像一根绳子。这是我的密码:
测试:

require 'rails_helper'

RSpec.describe TrelloToAc::Card do
  describe '#pic' do
    it 'return pic url from trello card' do
      result = @pic
      puts result
      expect(result).to be_a String
    end
  end
end

正在测试的代码:

class TrelloToAc::Card
  #
  #
  def pic
    @pic ||= card.attachments.last.url if card.attachments.any?
  end
  #
  #
end
8yoxcaq7

8yoxcaq71#

这就是我最终解决这个问题的原因。我认为这与我的一些评论者所说的更为接近。这还提供了有关 pic 测试:

require 'rails_helper'

RSpec.describe TrelloToAc::Card do

  let(:trello_card) do
    cassette = 'trello_to_ac/cards/get'
    VCR.use_cassette(cassette, match_requests_on: [:method]) do
      Trello::Card.find 'itZmoIG4'
    end
  end

  let(:email_sent_label) do
    cassette = 'trello_to_ac/labels/get'
    VCR.use_cassette(cassette, match_requests_on: [:method]) do
      Trello::Label.find '60db99d5230c123a1ab808d0'
    end
  end

  let(:trello_to_ac_card) do
    TrelloToAc::Card.new(trello_card, 32188, 147, email_sent_label)
  end

  describe '#pic' do
    it 'returns pic url from trello card' do
      cassette = 'trello_to_ac/attachments/get'
      result = VCR.use_cassette(cassette, match_requests_on: [:method]) do
        trello_to_ac_card.pic
      end
      expect(result).to be_a String
    end
  end
end

实际代码:

class TrelloToAc::Card
  attr_reader(
    :card, :order_number, :list_ac_campaign_id, :email_sent_label
  )

  def initialize(card, order_number, list_ac_campaign_id, email_sent_label)
    @card = card
    @order_number = order_number
    @list_ac_campaign_id = list_ac_campaign_id
    @email_sent_label = email_sent_label
  end

  def send_email_if_needed
    #
    #
    attach_trello_pic_to_ac_contact if pic
    #
    #
  end

  def pic
    @pic ||= card.attachments.last.url if card.attachments.any?
  end
end

这样,我测试的是类的一个示例,而不是示例变量。我对其他方法也有类似的测试。

相关问题