我试图运行这个rspec测试:
describe "quotes#approve action" do
it "should successfully change boolean called approved to true" do
get :approve
expect(@quote).to have_attributes(:approved => true)
expect(flash[:success]). to be_present
expect(response).to redirect_to admin_path
end
end
应从控制器调用此代码。
def approve
@quote.approved = true
end
但是当我运行此测试时,我收到此错误
Failure/Error: @quote.approved = true
NoMethodError:
undefined method `approved=' for nil:NilClass
我相当肯定这与我的@quote变量未分配有关,但即使在批准方法中设置布尔值之前,似乎也没有什么区别。由于这是我第一次遇到这样的问题,我不太确定从哪里开始调试它。
编辑:
我将rspec测试更改为:
describe "quotes#approve action" do
it "should successfully change boolean called approved to true" do
@quote = Quote.create(author: 'Test', saying: 'Hello!')
get :approve, id: @quote.id
expect(@quote).to have_attributes(:approved => true)
expect(flash[:success]). to be_present
expect(response).to redirect_to admin_path
end
end
和控制器代码:
def approve
@quote = Quote.find(params[:id])
@quote.approved = true
end
这似乎让我更进一步,因为我不再得到NoMethodError,但我现在得到一个新的错误,即:
Failure/Error: expect(@quote).to have_attributes(:approved => true)
expected #<Quote id: 102, author: "Test", saying: "Hello!", created_at: "2017-05-02 21:13:52", updated_at: "2017-05-02 21:13:52", approved: false> to have attributes {:approved => true} but had attributes {:approved => false}
Diff:
@@ -1,2 +1,2 @@
-:approved => true,
+:approved => false,
我相当肯定这只是意味着我的控制器代码无法正常工作,但我还没有能够弄清楚到底出了什么问题。