gpt4 book ai didi

ruby-on-rails-3 - rspec测试协会

转载 作者:行者123 更新时间:2023-12-04 05:21:16 25 4
gpt4 key购买 nike

我想在我的rspec Controller 测试中测试员工是否与公司关联。

我想在职员 Controller 的create操作中结束此操作:

staff.companies << current_company

从 session 变量中收集 current_company的位置。

如何为此编写测试?

我有这些模型
class Company < ActiveRecord::Base
has_many :employees
has_many :staff, :through => :employees
end

class Employee < ActiveRecord::Base
belongs_to :company
belongs_to :staff
end

class Staff < ActiveRecord::Base
has_many :employees
has_many :companies, :through => :employees
end

以下测试是我尝试指定关联的尝试,但在输入关联代码时失败:
    it "should belong to the current_company" do
staff.should_receive(:companies)
post :create
end

如果我在 Controller 中输入“staff.companies << current_company”代码,则在运行该测试时会收到以下错误消息:
 Failure/Error: post :create
NoMethodError:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<

职员 Controller 的创建方法:
  def create
@staff = Staff.new(params[:staff])

if @staff.save
@staff.companies << current_company
redirect_to staff_index_path, :notice => "Staff created successfully!"
else
@company = @staff.firm || current_company
flash[:alert] = "Staff failed to create"
render "new"
end
end

最佳答案

我将使用另一种方法,因为测试模型应该收到一定的消息会使测试与实现过于紧密地耦合在一起。您是否真的在乎公司是否收到#<<或其他方法?

确实,您要测试的是用户发布到页面时是否记录了用户的公司。记录方式无关紧要。所以我会做这样的事情:

it "should add the company to the user's list of companies" do
lambda do
post :create
end.should change(staff.companies, :count).from(0).to(1)
staff.companies.map(&:name).should include("Acme, Inc.")
end

这是测试行为而不是实现。好处是,当有人将 <<更改为等效的 push时,您的测试不会失败。它还具有使您的意图更加清楚的优点,因此可以更好地记录代码。

关于ruby-on-rails-3 - rspec测试协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5413543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com