可以在控制器规格中创建记录吗?

时间:2013-01-20 15:49:45

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

我写了以下例子:

it "should assign @services containing all the current user services" do
  customer = FactoryGirl.create(:user, fullname: "Iris Steensma")
  sign_in customer
  service = FactoryGirl.create(:service, user: customer)
  puts "Service.count = #{Service.count}" # Service.count = 0
  get :home
  assigns[:services].should eq([service])
end

动作控制器为:

def home
 #@services = curent_user.posted_services
 @services = Service.all
end

而factory.rb包含:

FactoryGirl.define do

  sequence :address do |n|
    "Street #{n}"
  end

  factory :user do
    fullname "Foo Bar"
    email { "#{fullname.gsub(' ', '.').downcase}@example.com" if fullname }
    password "secret"
  end

  factory :preference do
    profile "customer"
    user
  end

  factory :service do
    status :pending
    source_addr { generate(:address) }
    target_addr { generate(:address) }
    passenger "Mis Daysi"
    start_at Time.now
    offer 5
    payment "cash"
    user
  end

end

为什么Factory Girl无法创建服务记录?工厂在测试环境“rails c test”

中工作正常

这是rspec输出:

Failures:

  1) UsersController GET home should assign @services containing all the current user services
     Failure/Error: assigns[:services].should eq([service])

       expected: [#<Service:0x460d8ea @name="Service_1003">]
            got: []

       (compared using ==)

       Diff:
       @@ -1,2 +1,2 @@
       -[#<Service:0x460d8ea @name="Service_1003">]
       +[]

     # ./spec/controllers/users_controller_spec.rb:26:in `block (3 levels) in <top (required)>'

Finished in 1.03 seconds
3 examples, 1 failure

2 个答案:

答案 0 :(得分:0)

我相信正确的语法是:

assigns(:service).should eq([service])

根据rspec文档assigns[key]曾经是分配实例变量的方式,看起来有点像你正在发生的事情。

https://github.com/rspec/rspec-rails

答案 1 :(得分:0)

首先,用户:不需要客户,因为您正在使用已经这样做的customer.services.create

service = customer.services.create(attributes_for(:service, user: customer))

其次,在service = customer.services.create之后尝试这样做

service.valid?
puts service.errors.inspect
puts service.user == customer

也许你也可以试试

service = FactoryGirl.create(:service, :user => customer)

另外,您确定在Service类上定义了关联吗?

#<Service:0x57856f4 @name="Service_1003">

应该是

#<Service:0x57856f4 @name="Service_1003" user="<your customer object">

您的工厂如何定义服务?