如何使用rspec和factorygirl测试invalid_attribute

时间:2016-09-07 21:45:12

标签: ruby-on-rails rspec factory-bot

我正在学习如何使用tutorial来测试rails。

在本教程的一部分,它展示了如何编写df1.zoo <- zoo(df1[,-1], as.POSIXlt(df1[,1], format = "%Y-%m-%d %H:%M:%S")) #set date to Index: Notice that column 1 is Timestamp type and is named as "TS" full.frame.zoo <- zoo(NA, seq(start(df1.zoo), end(df1.zoo), by="min")) # zoo object full.frame.df <- data.frame(TS = as.POSIXlt(index(full.frame.zoo), format = "%Y-%m-%d %H:%M:%S")) # conver zoo object to data frame full.vancouver <- merge(full.frame.df, df1, all = TRUE) # merge test:

invalid_attribute

我不明白require 'rails_helper' RSpec.describe ContactsController, type: :controller do describe "POST #create" do context "with valid attributes" do it "create new contact" do post :create, contact: attributes_for(:contact) expect(Contact.count).to eq(1) end end context "with invalid attributes" do it "does not create new contact" do post :create, contact: attributes_for(:invalid_contact) expect(Contact.count).to eq(0) end end end end :contact指向的位置。

:invalid_contact是否指向:contact课程?它似乎来自FactoryGirl's gh.如果是这样,那么我怎么能创建Contact,因为没有:invalid_contact类?

我已经尝试:invalid_contact但它仍然失败。

post :create, contact: attributes_for(:contact, :full_name => nil)

spec/factories/contacts.rb

首次测试,FactoryGirl.define do factory :contact do full_name { Faker::Name.name } email { Faker::Internet.email } phone_number { Faker::PhoneNumber.phone_number } address { Faker::Address.street_address } end end 通过。在模型上,存在验证with valid attributes。我要添加什么才能通过validates_presence_of :full_name, :email, :phone_number, :address测试?

2 个答案:

答案 0 :(得分:1)

工厂将使用具有相同名称的类。因此,您的:contact工厂将使用Contact类。您可以通过指定要使用的类来为无效联系人创建新工厂。

factory :invalid_contact, class: Contact do
  full_name nil
end

也可以使用特征来避免拥有两个不同的工厂。

FactoryGirl.define do
  factory :contact do
    full_name     { Faker::Name.name }
    email         { Faker::Internet.email }
    phone_number  { Faker::PhoneNumber.phone_number }
    address       { Faker::Address.street_address }

    trait :invalid do
      full_name nil
    end
  end
end

然后将其与attributes_for(:contact, :invalid)

一起使用

答案 1 :(得分:0)

您链接的教程说:

  

按照上面的规范,编写一个使用无效属性的规范   创建一个新的联系人。此规范应检查联系人不是   创建

因此,您需要使用:invalid_contact的示例来确定如何测试:contact

您只需在规范中添加let

  

使用let来定义memoized帮助器方法。该值将被缓存   在同一个示例中跨多个调用但不跨越示例。

     

来源:https://www.relishapp.com/rspec/rspec-core/v/3-5/docs/helper-methods/let-and-let

然后您的控制器规范将如下所示:

...
let(:invalid_contact) { create(:contact, name: nil) }

context "with invalid attributes" do
  it "does not create new contact" do
    post :create, contact: attributes_for(invalid_contact)
    expect(Contact.count).to eq(0)
  end
end
...

这样#post行动paramsinvalid_contact

中获取

或@fanta在评论中建议,您可以向工厂添加trait。我更喜欢我的方法,因为查看代码的其他人会在不查看invalid_contact工厂

的情况下知道为什么:contacts应该无效