rspec验证失败:NoMethodError和预期的<blah'foo_id:1'=“”>但是Foo_id不能为空

时间:2018-02-16 23:42:48

标签: ruby-on-rails rspec

这里有两个问题,都与rspec有关。

1)此NoMethodError来自shares方法以及Tradewanted_itemTrade.rb之间的关联。请参阅下面的规格/型号代码,您会看到我已定义wanted_item_id。我为什么得到NoM​​ethodError?

NoMethodError:
  undefined method `shares' for nil:NilClass

2)每次我将expect(subject).to be_valid放入一个语句中,测试失败,说它期望我在规范中描述的输出,但是它已经出现错误,&#34;并且该字段不能为空。为什么会这样?

Failure/Error: expect(subject).to be_valid
  expected #<Trade id: nil, trade_requester_id: 1, wanted_item_id:22> to be valid, but got errors: Trade requester can't be blank, etc, .....

这是我的测试:

require 'rails_helper'

RSpec.describe Trade, type: :model do
    subject { described_class.new }

    it "is valid with valid attributes" do
        subject.trade_requester_id = 1
        subject.wanted_item_id = 22
        subject.shares = 24
        subject.agreement = false
        expect(subject).to be_valid
    end

  it "is valid with a trade_requester" do
        subject.trade_requester_id = 1
        expect(subject).to be_valid
    end

  it "is not valid without a wanted_item" do
    subject.wanted_item_id = 22
    expect(subject).to be_valid
  end
end

这是我的模特:

class Trade < ActiveRecord::Base    
  belongs_to :trade_requester, class_name: "User"
  belongs_to :wanted_item, class_name: "Item"

    validates :trade_requester, :wanted_item, presence: true
    validates :shares, numericality: { only_integer: true, greater_than_or_equal_to: 0, 
                                    less_than_or_equal_to: :max_shares }
    validates :agreement, presence: true

    scope :unapproved, -> { where(approved: nil) }
    scope :approved, -> { where(approved: true) }

    def max_shares
        wanted_item.shares
    end
end

1 个答案:

答案 0 :(得分:0)

你看到了:

NoMethodError
  undefined method `shares' for nil:NilClass

因为subjectnil且课程Nil没有shares方法。

您需要正确设置subject。我不熟悉您正在使用的语法。

这样做的常见模式是创建工厂并为准备好的协会提供有效数据。

或者你可以像这样设置:

describe Trade do
  let(:trade_requester){ TradeRequester.create(valid attrs) }
  let(:wanted_item    ){ WantedItem.create(valid attrs)     }

  it "is valid with valid attributes" do
    trade = Trade.new(trade_requester: trade_requester, wanted_item: wanted_item, shares: 21)
    expect( trade ).to be_valid
  end
end