【问题标题】:rspec expect redirect_to failrspec期望redirect_to失败
【发布时间】:2014-05-13 09:04:11
【问题描述】:

有时新的(非常干燥的)rspec 语法让我抓狂...

Rspec v 2.14.1

describe "POST create" do
  subject { post :create, contractor: valid_params }

  context "by user" do
    before { sign_in @legal.user }

    it "contractor successful created" do
      expect { subject }.to redirect_to(contractor_path(assigns(:contractor).id))

我在这里有错误和问题:

 NoMethodError: # :contractor variable not defined
   undefined method `id' for nil:NilClass

似乎expect 在控制器方法post 执行之前取了一个运算符,因为我试图引发这个方法。

我的代码:

def create
  @contractor = Contractor.restrict!(current_accreditation).new(permitted_params) # TODO move to the IR::Base
  if @contractor.save
    current_accreditation = @contractor.create_legal!(user: current_user) # TODO legal create
    redirect_to(@contractor)
  else
    render(:new)
  end
end

其次,为什么我在尝试的时候会出错

expect(subject).to ...

为什么{} 有效,但() 无效?在津津乐道的文档中,这种方法效果很好:https://www.relishapp.com/rspec/rspec-rails/docs/matchers/redirect-to-matcher

【问题讨论】:

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


    【解决方案1】:

    有点无关,但我发现以下内容很有帮助:

    • 当您想在块中的任何内容之前/之后进行测试时,请使用 expect {}。例如。 expect { subject } to change(User, :count) - 你想在之前和之后检查计数,以计算出差异,看看它是否真的改变了。

    • 使用expect () 来验证区块的结果,例如。发生了重定向,或者分配了某些东西等。

    您使用 assigns(:contractor) 的测试不起作用,因为您使用的是 {} 表示法 - 所以它试图在评估主题之前和之后(当然,在主题之前)都计算出 assigns(:contractor).id ,它不存在)。

    【讨论】:

    • 它对几个测试有帮助(有很多测试),但似乎it { expect{subject}.to change(controller, :current_accreditation).from(@legal).to(assigns(:contractor).legal) } 也以@contractor 开头。有什么办法可以避免吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多