我正在使用Ruby on Rails,RSPEC和Factory Girl在我的联系人控制器中为我的帖子操作编写测试:这是我的测试:
describe "POST CREATE" do
it "assigns @contact and redirects" do
contact = FactoryGirl.create(:contact, user_id: @user.id)
post :create, contact: FactoryGirl.attributes_for(:contact)
expect(assigns(:contact)).to eq([contact])
expect(response).to redirect_to(root_path)
end
end
这是我正在测试的控制器:
def create
# render text: params
@contact = Contact.new(contact_params)
@contact.user=current_user
if @contact.save
redirect_to root_path, notice: "Contact Created"
else
flash[:alert] = "Couldnt Create"
render 'new'
end
end
以下是用户工厂:
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
password { "32423fdsfasf42" }
factory :user_with_contacts do
transient do
contacts_count 2
end
after(:create) do |user, evaluator|
create_list(:contact, evaluator.contacts_count, user: user)
end
end
end
end
最后,这是我得到的错误:
expected: [#<Contact id: 412, first_name: "Alia", email: "janet@weimann.name", phone_number: "6044339393", created_at: "2015-09-12 20:02:12", updated_at: "2015-09-12 20:02:12", last_name: "Schultz", user_id: 2703>]
got: #<Contact id: 413, first_name: "Reggie", email: "kaley.kohler@ratke.org", phone_number: "6044339393", created_at: "2015-09-12 20:02:12", updated_at: "2015-09-12 20:02:12", last_name: "Zulauf", user_id: 2703>
(compared using ==)
Diff:
@@ -1,10 +1,10 @@
-[#<Contact:0x007ff74723ece0
- id: 412,
- first_name: "Alia",
- email: "janet@weimann.name",
- phone_number: "6044339393",
- created_at: Sat, 12 Sep 2015 20:02:12 UTC +00:00,
- updated_at: Sat, 12 Sep 2015 20:02:12 UTC +00:00,
- last_name: "Schultz",
- user_id: 2703>]
+#<Contact:0x007ff744e02340
+ id: 413,
+ first_name: "Reggie",
+ email: "kaley.kohler@ratke.org",
+ phone_number: "6044339393",
+ created_at: Sat, 12 Sep 2015 20:02:12 UTC +00:00,
+ updated_at: Sat, 12 Sep 2015 20:02:12 UTC +00:00,
+ last_name: "Zulauf",
+ user_id: 2703>
似乎正在创建两个联系人,一个接一个 - 为什么会发生这种情况?
答案 0 :(得分:1)
这是因为您创建了两个不同的联系人。 contact = FactoryGirl.create(:contact, user_id: @user.id)
和post :create, contact: FactoryGirl.attributes_for(:contact)
会创建两个联系人。
你应该写这样的东西
post :create, contact: FactoryGirl.attributes_for(:contact)
contact = Contact.last
expect(assigns(:contact)).to eq(contact)
expect(response).to redirect_to(root_path)