rspec关联测试失败

时间:2012-08-01 13:18:52

标签: ruby-on-rails rspec

对于rspec仍然有点新,并且无法通过以下测试(问题区域'它'应该以正确的顺序“do”阻止正确的处理):

user_spec.rb

describe User do

    before do
        @user = User.new(name: "Example User", email: "user@example.com",
                        password: "foobar", password_confirmation: "foobar")
    end

    describe "treating associations" do
        before { @user.save }
        let!(:older_treating) do
            FactoryGirl.create(:treating, user: @user, created_at: 1.day.ago)
        end
        let!(:newer_treating) do
            FactoryGirl.create(:treating, user: @user, created_at: 1.hour.ago)
        end

        it "should have the right treatings in the right order" do          
            @user.sent_treatings.should == [newer_treating, older_treating]
            @user.received_treatings.should == [newer_treating, older_treating]
        end
    end

end

根据我的用户和治疗模型,我知道我需要在测试中的某个地方嵌入“请求者”和“被请求者”,我尝试了不同的变体,但它们都继续失败。以下是模型:

user.rb

class User < ActiveRecord::Base
    attr_accessible :name, :email, :password, :password_confirmation
    has_secure_password

    has_many :sent_treatings, :foreign_key => "requestor_id", :class_name => "Treating"
    has_many :received_treatings, :foreign_key => "requestee_id", :class_name => "Treating"
end

treating.rb

class Treating < ActiveRecord::Base
  attr_accessible :intro, :proposed_date, :proposed_location

  validates :requestor_id, presence: true
  validates :requestee_id, presence: true

    belongs_to :requestor, class_name: "User"
    belongs_to :requestee, class_name: "User"

    default_scope order: 'treatings.created_at DESC'

end

这是我的factories.rb文件:

factories.rb

FactoryGirl.define do
    factory :user do
        sequence(:name) { |n| "Person #{n}" }
        sequence(:email) { |n| "person_#{n}@example.com"}
        password "foobar"
        password_confirmation "foobar"

        factory :admin do
            admin true
        end
    end

    factory :treating do
    intro "Lorem ipsum"
    user
  end
end

寻找适当代码填写'it'背后的逻辑解释应该以正确的顺序“do”阻止user_spec测试。谢谢!

编辑:抱歉,忘记了错误消息,这里是:

故障:

1)用户对待关联应该以正确的顺序进行正确的处理      失败/错误:FactoryGirl.create(:treat,user:@ user,created_at:1.day.ago)      NoMethodError:        '

中未定义的方法user=' for #<Treating:0x0000010385ec70> # ./spec/models/user_spec.rb:143:in阻止(3个级别)

1 个答案:

答案 0 :(得分:0)

您正在尝试覆盖不存在的字段。

您没有用户,只有请求者或被请求者。 试试例子

FactoryGirl.create(:treating, requestor: @user, created_at: 1.hour.ago)