我正在测试CapyBara的场景,我希望该记录无效。
Given "the customer is not an athlete" do
@customer = create(:athlete, :shop=> @shop, :first_name=>"Birglend", :last_name=>"Firglingham", :email=>"birglendfirglingham@gmail.com")
end
Then "I should not see that the customer is an athlete" do
expect(page).not_to have_css('.athlete-row')
end
但在它可以进入“Then”之前,我得到一个“ActiveRecord :: RecordNotSaved”异常。这是由before_save回调引起的,我必须检查客户是否是运动员。如果他们不是运动员,则该方法返回false并且我不希望保存记录。例如
before_save :check_athlete_status
def check_athlete_status
#return false unless self is an athlete
end
但我觉得这不是正确的方法,因为这是一个预期的场景,不应该抛出异常。我该如何处理?
答案 0 :(得分:1)
我认为你应该只使用验证而不是before_save。您通常希望在创建/保存回调之前和之后避免,除非您确实需要它们。也就是说,如果这是期望的行为,您可以期望调用引发异常。
答案 1 :(得分:1)
您正在尝试混合模型测试和功能测试。
有几种方法可以测试它。
我将删除Given
/ Then
语法,因为我没有任何使用该gem的经验。
1)型号规格:
RSpec.describe Athlete, type: :model do
context 'with invalid status' do
let(:athlete) { FactoryGirl.build(:athlete, :shop=> @shop, :first_name=>"Birglend", :last_name=>"Firglingham", :email=>"birglendfirglingham@gmail.com") }
it "raises an exception" do
expect { athlete.save }.to raise_exception(ActiveRecord::RecordNotSaved)
end
end
end
2)您还可以更改功能测试以通过界面执行Given
正在执行的操作:
feature 'Admin creates athlete' do
given(:athlete) { FactoryGirl.build(:athlete, :shop=> @shop, :first_name=>"Birglend", :last_name=>"Firglingham", :email=>"birglendfirglingham@gmail.com") }
scenario 'with invalid status' do
# We're testing that your custom callback stops saving the record.
visit '/athletes/new'
select @shop.title, from: 'Shop'
fill_in 'First name', with: 'Birglend'
fill_in 'Last name', with: 'Firglingham'
fill_in 'Email', with: 'birglendfirglingham@gmail.com'
select 'Not an athlete' from: 'Status'
click_button 'Create Athlete'
expect(page).to have_content 'There was an error creating the athlete'
# I'd argue that these next lines, what you're trying to test, really shouldn't be tested here. What you should be testing is that the form provides feedback that the athlete record wasn't created.
click_link 'Athletes'
expect(page).not_to have_css('.athlete-row')
end
end
我不知道你的界面应该做什么,所以我在上面做了些什么。希望能帮助你走上正确的道路。